简体   繁体   中英

Are Asp MVC Async Controller Actions Automatically Async?

In ASP.NET MVC when you create an async action with it's completed action does it automatically get processed asynchronously?

Example:

If I were to have a single long running task without declaring a delegate does the async void automatically run in a background thread?

   public void NewsAsync(string city) {

    AsyncManager.OutstandingOperations.Increment();
    NewsService newsService = new NewsService();
    AsyncManager.Parameters["headlines"] = newsService.GetHeadlines;
    AsyncManager.OutstandingOperations.Decrement();
}

Or will it only do so if the long running task is an asynchronous task?

   public void NewsAsync(string city) {

    AsyncManager.OutstandingOperations.Increment();
    NewsService newsService = new NewsService();
    newsService.GetHeadlinesCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["headlines"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    newsService.GetHeadlinesAsync(city);
}

so in other words, I do not care if the method inside the void is async but I do care if the void it's self is async so as to free up IIS threads.

Your first code example doesn't make sense. The NewsAsync must return as fast as possible and delegate the work to some background thread. It is the NewsCompleted action that will pass the results to the view as in your second example.

As far as those background threads are concerned it will depend on how is this NewsService.GetHeadlinesCompleted method implemented. The best possible scenario for async controllers is having some long running I/O operations (such as web service calls, database queries, ...) which could be run using I/O Completion Ports . In this situation there is no thread being monopolized during the execution of the request. In other situations such as trying to execute synchronous operations asynchronously (which is what seems to me that you are trying in your first code example) the benefit of asynchronous controllers is very doubtful, could even make things worse.

For deeper understanding of asynchronous operations in ASP.NET I would recommend you the following article on MSDN . It discusses asynchronous pages but exactly the same notions apply for ASP.NET asynchronous controllers as internally they are implemented as asynchronous handlers (using the IHttpAsyncHandler interface).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM