The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework, .NET Core, or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using the async
keyword are referred to as async methods.
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task. (See "Return Types" section.)
// Here, it is Task because the return statement returns an integer.
// - The method name ends in "Async."
async Task AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
using (HttpClient client = new HttpClient())
{
// GetStringAsync returns a Task. That means that when you await the
// task you'll get a string (urlContents).
Task getStringTask = client.GetStringAsync("https://docs.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
}
The following characteristics summarize what makes the previous example an async method.
- The method signature includes an
async
modifier. - The name of an async method, by convention, ends with an “Async” suffix.
- The return type is one of the following types:
- Task<TResult> if your method has a return statement in which the operand has type
TResult
. - Task if your method has no return statement or has a return statement with no operand.
void
if you’re writing an async event handler.- Any other type that has a
GetAwaiter
method (starting with C# 7.0).
- Task<TResult> if your method has a return statement in which the operand has type
- The method usually includes at least one await expression, which marks a point where the method can’t continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method’s caller.
Sources:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
Comments