在此示例代码中,代码以同步方式运行。为什么任务阻塞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);
}发布于 2015-04-22 00:14:10
异步方法仍然运行在与调用者相同的线程上;它一碰到await调用就会返回给调用方。这就是为什么Thread.Sleep(5000)仍然阻塞线程的原因。
在异步等待域中,您应该使用Task.Delay:
await Task.Delay(5000);https://stackoverflow.com/questions/29785390
复制相似问题