Three things are needed to use async-await
:
Task
object: This object is returned by a method which is executed asynchronously. It allows you to control the execution of the method.await
keyword: "Awaits" a Task
. Put this keyword before the Task
to asynchronously wait for it to finishasync
keyword: All methods which use the await
keyword have to be marked as async
A small example which demonstrates the usage of this keywords
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);
}
}
Some things to note:
Task<string>
or similar. The await
keyword waits till the execution of the method finishes and returns the string
.Task
object simply contains the status of the execution of the method, it can be used as any other variable.WebClient
) it bubbles up at the first time the await
keyword is used (in this example at the line var result (...)
)Task
object as MethodNameAsync