Async Method with Await in his Return

Asked

Viewed 416 times

1

public async Task<IHttpActionResult> NomeMetodo([FromUri] Filtro filtro)
{
    return await Task.Factory.StartNew(() =>Ok(_aplicacao.RetornarDados(filtro)));
}

I wonder why the above method makes sense, since it is async but I’m waiting for his return in await, Which to me looks like a normal synchronous method. I don’t know much about asyncs, you could explain to me?

  • 5

    You can see in my answer to this question where I discuss exactly this. Namely from Este mesmo método já retorna uma Task, o que quer dizer que é redundante usar async e await.

1 answer

2


In that case it really doesn’t make sense the use of async/await. Asymchronism is one way to inform a Thread that when a transaction occurs await that one Thread no need to wait for the result of await to process other information. This means that Thread that would be on idle time during a certain operation in which case you will be free to process other information while the operation await is not finalized.

However, asynchronous operations only make sense when you’re working with third-party resources, where processing will not be performed by the same feature as running your code. A very simple example of realizing this is when we consume third-party libraries through the protocol HTTP. Here is a (simplified) example taken from the MSDN:

async Task<int> AccessTheWebAsync()
{
    HttpClient client = new HttpClient();

    DoIndependentWork();

    string urlContents = await client.GetStringAsync("http://msdn.microsoft.com");

    return urlContents.Length;
}

Note that when making a call to the method Getstringasync here we are using the word reserve await, informing that this is an asynchronous operation. In this context it makes sense the use of asymchronism, we are making a call to an external service, where the processing is not performed by the same resources that manage our code, where the method resolution time can be several minutes because of bottlenecks that the site is facing or even some problem may occur. If processing is being done by another resource that is not mine, why should I lock the resources of a Thread, my resources could be free to solve other problems?

A more humane example for understanding:

We have a cook who is preparing an omelet. The cook has to perform various tasks to be able to prepare the omelette, such as breaking the eggs, stirring the eggs, putting salt into the scrambled eggs, and finally, placing the eggs in a skillet. Only our cook decided that he would put melted cheese on top of the omelet and use a microwave for it. See that all the actions of breaking the egg, stirring the eggs and putting salt inside the eggs need the cook to use their resources (your hands) to carry out these actions, only that heating the cheese is a microwave task, which only needs to receive the cheese (parameters). Obviously the cook needs to wait for the melted cheese to lay him on top of the eggs and serve himself, but does he need to stand in front of the microwave waiting for the cheese to be melted? Meanwhile, he could start preparing other dishes while the cheese is being melted.

Because the example posed in the question makes no sense?

In the code posted in the example there is no action that is carried out by third parties and that requires asymchronism. The asymchronism most likely should be in the method Returnees, only that it apparently does not have an asynchronous return. This could be corrected as follows:

public async Task<IHttpActionResult> NomeMetodo([FromUri] Filtro filtro)
{
    var dados = await _aplicacao.RetornarDadosAsync(filtro);
    return Ok(dados);
}

Note that the suffix of Async is a good practice to inform that the method has an asynchronous return, following a great principle of programming: Beginning of the smallest surprise.

I believe this method must be performing an operation in a database. Note that a third-party resource may even be a feature of your own machine. Operations I/O are examples of a use of asynchronism where the third party resource is performed by your own machine.

  • The answer seems to be correct, but talks a lot about thread, which is not even guaranteed to exist in a C#. Maybe you mean task.

  • Yes, that’s correct. I was writing and I was wrong in the terms.

Browser other questions tagged

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