Asynchronous programming with async and await

Asynchronous programming can help you enhance the responsiveness and performance of an application. In a traditional approach, it is difficult to write and maintain asynchronous code. However, C# 5 introduced two new keywords that simplify asynchronous programming: async and await. When encountered, the C# compiler does all the difficult work for you. It resembles synchronous code. Task and Task<T> are at the core of asynchronous programming.

Any I/O-bound or CPU-bound code can utilize asynchronous programming. In the case of IO-bound code, when you want to return a task from an async method, we use the await operation, whereas in CPU-bound code we wait for the operation that started a background thread using Task.Run.

When the await keyword is used, it returns control to the calling methods, thus allowing the UI to be responsive. 

Internally, when the compiler encounters the async keyword, it splits the method into tasks, and each task is marked with the await keyword. The await keyword generates code that will check whether the asynchronous operation has already completed; that is, the C# compiler transforms the code into a state machine that keeps track of the metadata related to each task/thread so that it can resume execution when the background task has finished executing:

private readonly HttpClient _httpClient = new HttpClient();

public async Task<int> GetDotNetCountAsync()
{
var html = await _httpClient.GetStringAsync("https://dotnetfoundation.org");

return Regex.Matches(html, @".NET").Count;
}

public void TestAsyncMethods()
{
Console.WriteLine("Invoking GetDotNetCountAsync method");
int count = GetDotNetCountAsync().Result;
Console.WriteLine($"Number of times .NET keyword displayed is {count}");
}

In the preceding code block, we are trying to find how many times a specific word has been used on a website. The output of the previous code is as follows:

Invoking GetDotNetCountAsync method
Number of times .NET keyword displayed is 22
Press any key to exit.

Here, we used the async keyword on the GetDotnetCountAsync method. Although the method is executed synchronously, the await keyword allows us to return to the calling method and wait until the async method has finished executing, which is when it returns the result.

It is important to understand that an async method body should always have an await, otherwise this method will never yield. No error is raised by the compiler either.

When writing asynchronous methods, you should always use async as the suffix. Note that async must be used for event handlers. This is the only method that allows async events handlers to work as events do not have return types.

You can read more about the Task-Based Asynchronous Pattern (TAP) from MSDN at https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.136.84