简体   繁体   中英

ASP.NET MVC Async Action doesn't work properly

I have an issue with this simple async code. The execution goes througth the TestAsync action and goes througth the delay method but when the delay method returns nothing else happens. it seems like blocked for some reason.

public async Task<ActionResult> TestAsync()
{
     try
     {
         var res = await doLongOperation();
         return RedirectToAction("Index");
     }
     catch (Exception e) { }
 }

 private Task<bool> doLongOperation()
 {
     var test = new Task<bool>(() => { /*do the long operation..*/ return true; });
     return test;
 }

Any suggestion?

new Task<bool>(() => true) returns a task that is not started yet. This is an old syntax that requires you to invoke the Start method on the task. If you don't invoke the Start method, the task will never complete, and thus asynchronous execution will never continue ( await will asynchronously wait forever).

If you simply want to delay execution, then simply use Task.Delay like this:

private async Task<bool> delay()
{
    await Task.Delay(1000);

    return true;
}

In general, it is always recommended to create tasks that are already started upon creation.

If you want to create a task that runs on a thread-pool thread, then use the Task.Run method.

The method posted in your question doesn't work properly because the task is not started, there's nothing finishing so your await is waiting indefinitely. If you want to use Async it's best to use async all the way down, especially in an ASP.NET context. If you are not doing anything that is truly asynchronous, then in a web development context, just allow it to be synchronous.

I honestly believe the most good that will be done here is for you to spend time studying async/await, an excellent resource is found here: Stephen Cleary Blog on Async

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