Async PartialView causes "HttpServerUtility.Execute blocked..." exception

BrunoLM picture BrunoLM · Jun 6, 2014 · Viewed 45.3k times · Source

I have a partial view that tries to retrieve a IEnumerable<Post> from the database using async...

Method

public static class PostService
{
    public static int PostsPerPage = 50;

    public static async Task<IEnumerable<Post>> GetRecentAsync(int page = 0)
    {
        return await entityFrameworkDbContext.Posts
            .ToListAsync();
    }
}

PartialView

public async Task<ActionResult> Recent(int page = 0)
{
    return PartialView(await PostService.GetRecentAsync(page));
}

And then if I try to call it

@Html.Action("Recent", "Post")

I get the following exception

HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete.

Why do I get this error? Shouldn't it work?

Answer

Xenolightning picture Xenolightning · Jun 11, 2014

Child actions must be invoked synchronously. Issue 601 I am also not aware of any recent updates to the current MVC libraries allowing this functionality.

A comment on Issue 601, hints at this functionality being added in MVC vNext, aka. MVC6. Child actions look to be replaced with ViewComponent which can be invoked asynchronously from a view as below. Full examples here and here

<div>
@await Component.InvokeAsync("YourComponent")
</div>

For more on MVC6 check out, http://www.asp.net/vnext/overview/aspnet-vnext/overview

Note: This answer is just a formality, so the question can be marked as answered