Task definitions

The Task type represents asynchronous tasks. The Task class is a representation of a unit of work. We can find similar concepts in other languages. For example, in JavaScript, the concept of Task is represented by a Promise.

It is common to associate a Task type with a thread in our CPU, which is not correct: wrapping a method execution in a Task doesn't guarantee that the operation will be executed on another thread. 

The async and await keywords are the easiest way to deal with asynchronous operations in C#: the async keyword converts the method into a state machine and it enables the await keyword in the implementation of the method. The await keyword indicates to the compiler the operations that need to be awaited in order to proceed with the execution of the asynchronous method. Therefore, it is common to find something similar in C# codebases:

public async Task<String> GetStringAsync(String url)
{
var request = await _httpClient.GetAsync(url);
var responseContent = await request.Content.ReadAsStringAsync();
return responseContent;
}

The preceding snippet is very intuitive: it calls a url using the GetAsync method of the _httpClient instance, and it uses ReadAsStringAsync to get the resulting string and store it in the responseContent object. It is essential to understand that async and await are syntactic sugar keywords, and the same result can be achieved in a less readable way by using the ContinueWith method:

public Task<String> GetStringAsync(String url) 
{
var request =_httpClient.GetAsync(url);
var responseContentTask = request.ContinueWith(http =>
http.Result.Content.ReadAsStringAsync());
return responseContentTask.Unwrap();
}

This code snippet has the same effect as the previous one. The main difference is that this code is less intuitive. Furthermore, in complex operations that execute a lot of nested transactions, we would create a lot of nesting levels. 

It is essential to embrace the async/await syntax as the primary way of working with asynchronous code. Other languages have taken a similar approach to keep the code more clean and readable. This is the case for ECMAScript, which introduced the async/await syntax in ES 2016: https://github.com/tc39/ecma262/blob/master/README.md.
..................Content has been hidden....................

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