What are Async methods?


I noticed that most methods in C # have an equal method but with a name async .

What are these methods and how do they work?

asked by anonymous 05.01.2017 / 02:13

2 answers


They are methods that execute asynchronously, that is, the called one does not have to wait for its execution and the execution can continue normally without locking, when the asynchronous method called ends it can return to the point where it was called and give continuity to that was doing. This is done with the await keyword that has already been explained in In C #, what is the await keyword for? / a>. Its operation is explained in this question, it is basically a state machine that regulates execution between the normal and asynchronous execution line.

It is a convention that these methods terminate with the suffix Async .

Asynchronous processing and synchronous processing have also been discussed in What are asynchronous processing and synchronous processing? .

A practical example of the difference: What is the difference between ToListAsync () and ToList ()?

You'll probably want to know about Difference between Task and Thread and a practical example of its use: What are the pros and cons of Task < List > > about List .

In operations the response will be very fast its use is not worth, this is useful when there is some waiting, something like 50ms, but always depends on the case, may be less or more. So saying that most methods have Async in name is force of expression :) After all the majority runs in the house of micro or nanoseconds.

05.01.2017 / 02:28

They are asynchronous methods like @Maniero mentioned, just to complement the explanation and you understand better, we often use async to consume a Httpclient service in a Winforms or WPF application. For example:

static async Task<Product> GetProductAsync(string path)
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
        product = await response.Content.ReadAsAsync<Product>();
    return product;

This method will make a request of type "GET" to a web service, to receive this object Product its function would look like this:

private async void GetProduct(){
 string url = "http://localhost:50500/MyController/MyAction/ProductId";
 var product = await GetProductAsync(url);

Whenever you call an asynchronous method, the scope of the function must have async before the return type, and the function call must have await before the method name. Basically this is how I use these types of functions.

05.01.2017 / 02:52