I have a need for creating a child action in a controller in my side project. I’ve been using async everywhere else in the application so it’s obvious that I’m going to make this child action async. My child action is similar to the example below:
[ChildActionOnly] public async Task<ActionResult> SampleChildAction() { // Call an asynchronous method await Task.Delay(5000); return PartialView("_SampleChildActionView"); }
When I call the child action in a view using @Html.Action, I get this error.
Error executing child request for handler ‘System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper’. HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete
It turns out that child actions cannot be run asynchronously in MVC. My research shows that the recommended approach is to avoid using async method in child actions.
However, there is a way to call async methods within child actions if you really need to use child actions and they have to call async methods. You could make the child action synchronous and use Task.Run to run the async methods and do the awaiting for you.
[ChildActionOnly] public ActionResult SampleChildAction() { // Call an asynchronous method Task.Run(async () => { await Task.Delay(5000); }).Result; return PartialView("_SampleChildActionView"); }
Even though that would make it work, I would avoid using async in child actions all together as the solution is a bit hacky. In MVC 6, however, child actions no longer exist. They are replaced by view components which can be run async. More on MVC view components in another post.
Mohsin Khan
Nice Post to achieve async in child action method, Though I have look into code and after that jump in .net source code.
I found something interesting “Result” will be available if Task is generic “Task” .
Below source code snippet from microsoft reference .Net Framework 4.7.1
1) public class Task : Task
2) which have Result property.
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TResult Result
{
get { return IsWaitNotificationEnabledOrNotRanToCompletion ?
GetResultCore(waitCompletionNotification: true) : m_result; }
}
If try to access “Result” using “Task” this will give compile error.
Share your input.
Thank
Mohsin Khan
borvestinkral
Nice post. I was checking constantly this weblog and I am inspired! Extremely helpful information specially the final part 🙂 I care for such info a lot. I was seeking this certain info for a very long time. Thank you and good luck.
more info
Right here is the perfect webpage for everyone who hopes to understand this topic. You know so much its almost tough to argue with you (not that I personally would want to…HaHa). You definitely put a new spin on a topic that’s been discussed for ages. Great stuff, just wonderful!