简体   繁体   中英

Async actions in asp.net mvc application

I'm trying to implement an asynchronous action in ASP.NET MVC. The code looks like follows:

[HttpGet]
public async Task<string> HeavyAction(int holdTime)
{
      await Task.Delay(holdTime);
      return "Now I'm done!";
}

This action shows the main problem, that's when the user calls the action with a big parameter value (10000) the application isn't responsive - the request is sent but the browser is waiting for the response. I think so shouldn't look an asynchronous request. In my opinion the user should be able to call other actions in the mean time.

Could somebody help me with my problem? Thanks! :-)

I think so shouldn't look an asynchronous request.

You have a misunderstanding of how "async-await" works. When your method awaits on an async method, control is yielded back to the caller, in this case the ASP.NET runtime. But, async-await does not change the request-response nature of the HTTP protocol. Thus, only once Task.Delay completes, the next line of code executes and returns a response to the caller.

What you're thinking of is a "fire and forget" style of execution where you queue a delegate on the threadpool and immediately return control. Such nature isn't really suited for ASP.NET and will certainly hurt performance if your app needs any sort of scale.

When you use 'await', you are telling C# to wait for the action to finish. Try calling your async method without the 'await' keyword. Like:

[HttpGet]
public async Task<string> HeavyAction(int holdTime)
{
      Task.Delay(holdTime);
      return "Now I'm done!";
}

so the method will return immediately and execute Task.Delay later.

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