在此示例代码中,代码以同步方式运行。为什么任务会阻塞 DoIndependentWork() 而不是仅在 webTask.Result 中阻塞?我知道我可以使用 Task.Run() 和其他东西,但我试图更好地理解异步和等待。
static void Main(string[] args)
{
var webTask = AccessTheWebAsync();
DoIndependentWork();
Console.WriteLine("AccessTheWebAsync result: {0}", webTask.Result);
Console.ReadLine();
}
static async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
Thread.Sleep(5000);
Console.WriteLine("AccessTheWebAsync in Thread {0}", Thread.CurrentThread.ManagedThreadId);
var urlContents = await client.GetStringAsync("http://msdn.microsoft.com");
return urlContents.Length;
}
static void DoIndependentWork()
{
Console.WriteLine("DoIndependentWork in Thread {0}", Thread.CurrentThread.ManagedThreadId);
}
最佳答案
您的异步方法仍然与调用者在同一个线程上运行;它只会在遇到 await
调用时立即返回给调用者。这就是 Thread.Sleep(5000)
仍然阻塞线程的原因。
在异步等待领域,你应该使用 Task.Delay
代替:
await Task.Delay(5000);
关于c# - 控制台应用程序中的异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29785390/