[英]Why is invoking a method on the same line as awaiting it considered asynchronous?
我正在查看http://www.dotnetperls.com/async上的示例以更好地理解async / await,但以下內容讓我感到困惑:
我理解為什么下面的例子被認為是異步的。 調用HandleFileAsync ,調用Console.WriteLine ,然后在繼續之前等待任務完成。
static async void ProcessDataAsync()
{
// Start the HandleFile method.
Task<int> task = HandleFileAsync("C:\\enable1.txt");
// Control returns here before HandleFileAsync returns.
// ... Prompt the user.
Console.WriteLine("Please wait patiently " +
"while I do something important.");
// Wait for the HandleFile task to complete.
// ... Display its results.
int x = await task;
Console.WriteLine("Count: " + x);
}
但是在下面的示例中,我們等待對Task.Run的調用,該調用運行一個動作:
static async void Example()
{
// This method runs asynchronously.
int t = await Task.Run(() => Allocate());
Console.WriteLine("Compute: " + t);
}
那么,如果我們在等待 Task.Run的完成,那么異步發生了什么呢? 我們認為一旦我們等待后續任務的執行完成就會成為阻塞調用,在這種情況下,在同一行上調用它。
我錯過了什么?
我們認為一旦我們等待后續任務的執行完成就會成為阻塞調用,在這種情況下,在同一行上調用它。 我錯過了什么?
你的信念是錯誤的; 這就是你所缺少的。 “等待”的意思是“現在返回,在我們異步等待時運行別的東西,當結果可用時,回到這里。”
獲取任務的結果會做您認為等待的事情。 如果它只是同步獲取任務的結果,我們就不必發明等待! 它異步獲取任務的結果。
雖然我們在這,但這個評論是錯誤的:
// Control returns here before HandleFileAsync returns.
怎么可能呢? HandleFileAsync返回了一個任務! 如果HandleFileAsync沒有返回,控制如何通過手頭的任務達到這一點? 當然它回來了。
這條評論具有誤導性:
// Wait for the HandleFile task to complete.
這應該是異步等待任務完成。 通過異步等待,記住,我們的意思是“現在返回,繼續運行更多的工作,當任務完成時,在此時恢復結果。”
如果我是你,我會找到更好的教程。
到底發生了什么異步?
考慮一下:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static volatile uint i;
static uint Test()
{
Thread.Sleep(1000);
i = 2; //uint.MaxValue;
while (i-- > 0) { }
return i;
}
static bool done;
static async void Example()
{
var t = await Task.Run(() => Test());
Console.WriteLine("result: " + t);
done = true;
}
static void Main(string[] args)
{
Example();
Console.WriteLine("wait: Control returns here before Example() returns ");
while (!done) { }
Console.WriteLine("done ");
}
}
}
Example();
本身就是異步發生的。 所以,如果你刪除while (!done) { }
程序在Example()
完成之前退出。
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.