Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

asynchronous - ASP.NET MVC4 Async controller - Why to use?

I am trying to understand why and when should I use an async controller action. Eventually, when I use await in it, it will wait for the operation to complete in order to return the View.

For example

public async Task<ActionResult> TryMe()
{
   await SomeActionAsync();
   return View();
}

In this case if I use the async or not using the async, the Action will take the same time to execute.

If I am not trying to run at least 2 slow operations (that are not dependent on each other) in parallel, I don't see any reason to use an async controller action.

Please correct me if I'm wrong. I think I'm missing something here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The point of the await keyword is to let you work with asynchronous operations without writing ugly callbacks.

Using asynchronous operations helps avoid wasting thread pool threads.

Explanation

ASP.Net runs all of your code in threads from the managed thread pool.
If you have too many slow requests running at once, the thread pool will get full, and new requests will need to wait for a thread to get free.

Frequently, however, your requests are slow not because they're doing computation (compute-bound), but because they're waiting for something else, such as a hard disk, a database server, or an external webservice (IO- or network-bound).

There is no point in wasting a precious threadpool thread simply to wait for the external operation to finish.

Asynchronous operations allow you to start the operation, return your thread to the pool, then "wake up" on a different thread pool thread when the operation is finished.
While the operation is running, no threads are consumed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...