What are Async methods?

Asked

Viewed 5,495 times

15

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

What are these methods and how they work?

2 answers

14


They are methods that can run asynchronously, IE, who called does not need to wait for its execution and it can continue normally without blocking the application, So when the asynchronous method called ends he can go back to the point where he was called and continue what he was doing. This is done with the keyword await which has already been explained in In C#, what is the await keyword for?. Its operation is explained in this question, it is basically a state machine that regulates the execution between the normal and asynchronous execution line.

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

It has also been talked about asymchricity in What are asynchronous processing and synchronous processing?.

A practical example of difference: What 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 implementing Task<List<Object>> on List<Object>.

In operations that the answer will be very fast its use is not worth it, this is useful when there is some wait, something like 50ms, but always depends on the case, can be less or more. So to say that most methods have Async in the name is expression force :) After all most perform in the house of micro or nanoseconds.

  • So async methods would be like having a thread just for them?

  • @viniciusafx not exactly. In these links I even talk about it, he never creates threads. Task can create thread if necessary. But it roughly has a similar effect.

5

These are asynchronous methods as @Maniero mentioned, just to complement the explanation and you understand better, we often use async to consume a service Httpclient 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 should have the async before the return type and the function call should have await before the method name. Basically this is how I use these types of functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.