I have written the following (a plain Console application) to test my understanding about async and await in C#.
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Async result: " + getLengthFromWebsiteAsync());
}
public static async Task<int> getLengthFromWebsiteAsync()
{
HttpClient httpClient = new HttpClient();
Task<string> sampleTask = httpClient.GetStringAsync("http://www.adobe.com");
Console.WriteLine("Before the await: ");
int lengthRequired = (await sampleTask).Length;
Console.WriteLine("After the await: " + lengthRequired.ToString());
return lengthRequired;
}
The following is the result that I got upon running:
Before the await:
Async result: System.Threading.Tasks.Task'1[System.Int32]
My question is, isn't the line "After the await: " supposed to show up? Am I on the wrong track in understanding the flow of async/await?
Currently you're starting the operation - but it's never completing. Your program is terminating before you do anything with the task.
As this is a console app, continuations will run on a thread-pool thread anyway, so you can change your code to make the Main
method block until the task has completed:
public static void Main(string[] args)
{
Console.WriteLine("Async result: " + getLengthFromWebsiteAsync().Result);
}
Normally you should be very careful about using Result
and Wait()
on tasks, as you can easily cause a deadlock. (For example, it wouldn't be safe to do the above in a WinForms UI - the Result
call would block the UI thread until the task completed... and the task would be waiting for the UI thread to become available to run the continuation after the await
in the async method.)
See more on this question at Stackoverflow