Rasmus Christensen
Rasmus Christensen

Reputation: 8541

Task running after request returns, any concerns?

I'm making an ASPNET MVC solution where I use async/await to make som external requests. When the tasks complete with a call to Task.WhenAll I have a ContinueWith, where I'm persisting some data to a database. I'm a bit new to async/await and what I discovered was that the request to my action returned and updated the UI, before the ContinueWith actually got called. This also means that If I need the users identity it must be passed to the Continue with while having the request context. Now do I need to do anything special to ensure that the server actually processes the request after the ActionResult (aspnet mvc) is returned? I remembered to have seen something about RunInBackground, but I'm not able to find it again.

The code in the Action is like

await Task.WhenAll(tasks).ContinueWith(OnTagsMetaCollected, result);


    return Json(result, JsonRequestBehavior.AllowGet);

First I make some tasks which all are executed. When all are complete I want to compute some new results, which is done inside the OnTagsMetaCollected, and added in the result (a list) The the modified result is returned from the action.

I'm not sure it's the best structure to solve this problem so any advice I would welcome :).

Upvotes: 0

Views: 173

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457057

The solution is quite simple: use await instead of ContinueWith. await will properly flow the request context (including user identity) to the rest of the async method.

Upvotes: 3

Related Questions