简体   繁体   中英

Aysnchronous OnActionExecuted on asp.net MVC Controller

I have a task that needs executing after a request has been processed by the controller and the response is on the way back to the client. To that end, I have overriden the OnActionExecuted() event on my controller and call the task inside this method.

As the task can take some time to run and also returns void, I want to call it asynchronously so that the overridden OnActionExecuted() method can return immediately and the response can be sent to the client while the task is executing. I have tried to implement this with the code below, using Task.Run() (in .net 4.5)

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    Task.Run(() => WrapUp());
}

However, this does not product the desired effect. When I step through the code it still executes synchronously - everything inside the WrapUp() method is called before the OnActionExecuted() method exits. When the WrapUp() method hangs, the client is left waiting for the task to complete before the response is received.

What do I need to do to make this work as intended?

The OnActionExecuted will return immediately because inside you are only creating and starting a task. The behavior you are observing is not normal. What happens if you try the following:

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    Task.Run(() => Thread.Sleep(10000));
}

The client is not waiting 10 seconds to get the result, is it?

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