Reputation: 6588
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?
Upvotes: 1
Views: 1785
Reputation: 1038710
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?
Upvotes: 3