最近我正在學習任務和certailly我感動異步等待,我試圖寫一個簡單的演示,請親切地幫助檢查我的編碼是否有任何問題?爲什麼「x = ???」和「GetDataFromDbAsync結束」不會打印在控制檯上?如果你能幫我解決問題,我會非常自信。非常感謝。等待之後的文本不能打印出異步無效的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
Console.WriteLine("main thread starts...");
System.Threading.Thread.Sleep(1000);
test.GetDataFromDb();
Console.WriteLine("Mainthread end");
Console.ReadKey();
}
}
class Test
{
public void GetDataFromDb()
{
Console.WriteLine("GetDataFromDb starts");
Task.Run(() => GetDataFromDbAsync());
Console.WriteLine("GetDataFromDb ends");
}
public async Task<bool> GetDataFromDbAsync()
{
try
{
Console.WriteLine("GetDataFromDbAsync starts");
var x = await ReadingDbAsync();
Console.WriteLine("x=" + x);
Console.WriteLine("GetDataFromDbAsync ends");
return true;
}
catch(AggregateException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
public Task<int> ReadingDbAsync()
{
Console.WriteLine("ReadingDbAsync starts");
System.Threading.Thread.Sleep(3000);
var task= new Task<int>(() => 100);
Console.WriteLine("ReadingDbAsync ends");
return task;
}
}
}
以下是輸出, demo output here
輸出如下:
main thread starts...
GetDataFromDb starts
GetDataFromDb end
Mainthread end
GetDataFromDbAsync starts
ReadingDbAsync starts
ReadingDbAsync ends
**BUT WHY NOT SHOW THE FOLLOWING
x=100
GetDataFromDbAsync ends**
非常感謝您的回答,這是可行的。 – Jacob