Async and await in MVC 4 Controller

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

Every time I try to use the new Async and Await operators and return a collection of objects from a database I get an Invalid Operation exception. When I use it to only return a single Item it works fine.

Controller Code:

public async Task EnvironmentList() {     EfEnvironmentDataAccess dataAccess = new EfEnvironmentDataAccess();     ICollection environments = await dataAccess.GetAllEnvironmentsAsync();     return PartialView(environments); }

View Code:

Table Dumps

@Html.Action("EnvironmentList", "Environment") @Html.Action("ComputerList", "Computer") @Html.Action("ProductList", "Product") @Html.Action("InstanceList", "Instance") @Html.Action("ProfileList", "Profile")

The Data Access Code:

public ICollection GetAllEnvironments() {     using (EcuWebDataContext db = new EcuWebDataContext())     {         return db.Environments.OrderBy(e => e.Name).ToList();     } }  public async Task> GetAllEnvironmentsAsync() {     return await Task.Run(() => GetAllEnvironments()); } 

The Error I get is:

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.

回答1:

First of all, you cannot use asynchronous processing with child actions and I suppose this is what you are trying to do.

Secondly, you are not doing any asynchronous processing here by spinning up another thread to execute your code with the below line of code:

Task.Run(() => GetAllEnvironments()); 

It will block a thread at the end of the day and you will have nothing but a context switch overhead. EF6 will have support for asynchronous processing. For asynchronous queries with pure ADO.NET, have a look:

Asynchronous Database Calls With Task-based Asynchronous Programming Model (TAP) in ASP.NET MVC 4



回答2:

It's been some time since this question was answered. But I was having a similar situation with MVC 5 and I was able to make a [ChildActionOnly] work asynchronously just by commenting out the following line under section of web.config file.

EDIT: Consider this a workaround while you find a real solution for your situation. Please see Leri's comments below.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!