簡單的用法
使用 async-await 需要三件事:
Task物件:該物件由非同步執行的方法返回。它允許你控制方法的執行。await關鍵字:等待一個Task。將此關鍵字放在Task之前,非同步等待它完成async關鍵字:所有使用await關鍵字的方法都必須標記為async
一個小例子,演示了這個關鍵字的用法
public async Task DoStuffAsync()
{
var result = await DownloadFromWebpageAsync(); //calls method and waits till execution finished
var task = WriteTextAsync(@"temp.txt", result); //starts saving the string to a file, continues execution right await
Debug.Write("this is executed parallel with WriteTextAsync!"); //executed parallel with WriteTextAsync!
await task; //wait for WriteTextAsync to finish execution
}
private async Task<string> DownloadFromWebpageAsync()
{
using (var client = new WebClient())
{
return await client.DownloadStringTaskAsync(new Uri("http://stackoverflow.com"));
}
}
private async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath, FileMode.Append))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
}
}
有些事情需要注意:
- 你可以使用
Task<string>或類似的非同步操作指定返回值。await關鍵字一直等到方法執行完畢並返回string。 Task物件只包含方法執行的狀態,它可以用作任何其他變數。- 如果丟擲異常(例如
WebClient),它會在第一次使用await關鍵字時冒泡(在此示例中為var result (...)) - 建議命名將
Task物件作為MethodNameAsync返回的方法