控制台应用程序中的异步

Async in Console Application

在此示例代码中,代码以同步方式运行。为什么任务阻塞 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 电话,它就会 returns 给呼叫者。这就是 Thread.Sleep(5000) 仍然阻塞线程的原因。

在异步等待领域,你应该使用Task.Delay代替:

await Task.Delay(5000);