Until now we have only used Task
with the await
operator. However, it is not the only type that is compatible with await
. Actually, the await
operator can be used with every type that contains the GetAwaiter
method with no parameters and the return type that does the following:
Implements the
INotifyCompletion
interfaceContains the
IsCompleted
boolean propertyHas the
GetResult
method with no parameters
This method can even be an extension method, so it is possible to extend the existing types and add the await
compatibility to them. In this example, we will create such a method for the Uri
type. This method will download content as a string via HTTP from the address provided in the Uri
instance:
private static TaskAwaiter<string> GetAwaiter(this Uri url) { return new HttpClient().GetStringAsync(url).GetAwaiter(); } var content = await new Uri("http://google.com"); Console.WriteLine(content.Substring(0, 10));
If we run this, we will see the first...