最近我嘗試瞭解異步編程的新C#功能,async/await關鍵字。當我在網上搜索時,我遇到過這樣的例子:C#中的異步編程#
static void Main(string[] args)
{
Console.WriteLine("Task based APM demo");
// Call Exponnent() asynchronously.
// And immediately return the control flow.
// If I don't put a Task here, the program will sometimes
// terminate immediately.
Task t = new Task(async() =>
{
int result = await Program.Exponent(10);
// After the operation is completed, the control flow will go here.
Console.WriteLine(result);
});
t.Start();
Console.ReadKey();
}
static async Task<int> Exponent(int n)
{
Console.WriteLine("Task started");
return await TaskEx.Run<int>(() => 2 << (n - 1));
}
}
我對此有疑問,以及這種說法的行爲方式。 首先,當我理解當我們想要釋放該過程並返回到調用者上下文時使用的await表達式。但爲什麼這個表達式在Exponent方法調用它的那條線上使用了這個表達式?事實上,當編譯器面對這一行程序時會發生什麼? 而字母問題是,爲什麼程序使用「TaskEx.Run」來返回Exponent方法體中的結果?是否有可能使用「return await(()=> 2 < <(n-1));」只要?編譯器如何處理這一行?
在此先感謝
我認爲這個問題應該有一個更具體的標題,但我不知道它應該是什麼。任何人有想法? – svick
@Azad:我建議你先介紹一下'async'(比如[我博客上的](http://nitoprograms.blogspot.com/2012/02/async-and-await.html))和然後使用[async/await FAQ](http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx)進行跟蹤。 –