gpt4 book ai didi

c# - MVC 4 Controller 中的异步和等待

转载 作者:可可西里 更新时间:2023-11-01 03:07:06 25 4
gpt4 key购买 nike

每次我尝试使用新的 AsyncAwait 运算符并从数据库返回对象集合时,我都会得到一个 Invalid Operation异常(exception)。当我用它只返回一个项目时,它工作正常。

Controller 代码:

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

查看代码:

<div class="ECURightCol">
<h3>Table Dumps</h3>
@Html.Action("EnvironmentList", "Environment")
@Html.Action("ComputerList", "Computer")
@Html.Action("ProductList", "Product")
@Html.Action("InstanceList", "Instance")
@Html.Action("ProfileList", "Profile")

数据访问代码:

public ICollection<Environment> GetAllEnvironments()
{
using (EcuWebDataContext db = new EcuWebDataContext())
{
return db.Environments.OrderBy(e => e.Name).ToList();
}
}

public async Task<ICollection<Environment>> GetAllEnvironmentsAsync()
{
return await Task.Run(() => GetAllEnvironments());
}

我得到的错误是:

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.

最佳答案

首先,you cannot use asynchronous processing with child actions我想这就是您想要做的。

其次,您没有通过启动另一个线程来执行任何异步处理,使用以下代码行执行您的代码:

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

它会在一天结束时阻塞一个线程,除了上下文切换开销之外,您将一无所有。 EF6 将支持异步处理。对于使用纯 ADO.NET 的异步查询,请查看:

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

关于c# - MVC 4 Controller 中的异步和等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com