[英]Entity Framework hangs when using async calls
I am new to using async and this seems to elude me on what the cause or issue is, when I attempt to load the webpage the async call seems to hang and the page is never loaded. 我是新手使用异步,这似乎让我不知道原因或问题是什么,当我尝试加载网页时,异步调用似乎挂起并且页面永远不会被加载。 Is my implementation wrong here?
这是我的实施错了吗?
CONTROLLER CONTROLLER
public ActionResult Index()
{
var model = _partyAddOnService.Get().Result.Select(x => new AddOnModel()
{
Id = x.Id,
AddOnType = x.AddOnType,
Description = x.Description,
Name = x.Name,
Price = x.Price
});
return View(model);
}
SERVICE 服务
public async Task<IEnumerable<AddOn>> Get()
{
return await _repository.GetAsync();
}
REPOSITORY REPOSITORY
public async Task<IEnumerable<T>> GetAsync()
{
return await Context.Set<T>().ToListAsync();
}
UPDATE: 更新:
I tried this as well and it still hangs... 我也尝试了这个,它仍然挂起......
public ActionResult Index()
{
var model = _partyAddOnService.Get();
return View();
}
* When debugging and looking at the Task status it says "Waiting for activation" *在调试并查看任务状态时,它显示“正在等待激活”
Also tried using the ConfigureAwait method as the article suggested. 还尝试使用ConfigureAwait方法,如文章所建议的那样。 (see James comment below)
(见詹姆斯评论如下)
public async Task<IEnumerable<AddOn>> Get()
{
return await _repository.GetAsync().ConfigureAwait(false);
}
To prevent deadlocks, just use async
all the way up. 为了防止死锁,只需一直使用
async
。 You're already using it in your service and repository, so just add it to your controller: 您已经在服务和存储库中使用它,所以只需将其添加到您的控制器:
public async Task<ActionResult> Index()
{
var model = (await _partyAddOnService.Get()).Select(x => new AddOnModel()
{
Id = x.Id,
AddOnType = x.AddOnType,
Description = x.Description,
Name = x.Name,
Price = x.Price
});
return View(model);
}
I also recommend that you change your async methods to end in Async
, to follow the Task-based Asynchronous Pattern . 我还建议您将异步方法更改为在
Async
结束,以遵循基于任务的异步模式 。 Ie, Get
should be GetAsync
. 即,
Get
应该是GetAsync
。
You are causing a deadlock, because you didn't implement the async-await pattern all the way up. 您正在导致死锁,因为您没有一直实现async-await模式。 Also use .ConfigureAwait(false) on the lowest level.
也可以在最低级别使用.ConfigureAwait(false)。
public async Task<ActionResult> Index()
{
var model = await _partyAddOnService.Get().Result.Select(x => new AddOnModel()
{
Id = x.Id,
AddOnType = x.AddOnType,
Description = x.Description,
Name = x.Name,
Price = x.Price
});
return View(model);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.