【发布时间】:2014-08-13 05:32:47
【问题描述】:
尽我所能,我一直选择异步。但是,我仍然坚持使用不是为异步构建的 ASP.NET Membership。因此,我对 string[] GetRolesForUser() 等方法的调用无法使用异步。
为了正确构建角色,我依赖来自各种来源的数据,因此我使用多个任务并行获取数据:
public override string[] GetRolesForUser(string username) {
...
Task.WaitAll(taskAccounts, taskContracts, taskOtherContracts, taskMoreContracts, taskSomeProduct);
...
}
所有这些任务都只是使用实体框架从 SQL Server 数据库中获取数据。但是,最后一个任务 (taskSomeProduct) 的引入导致了死锁,而其他方法都没有。
下面是导致死锁的方法:
public async Task<int> SomeProduct(IEnumerable<string> ids) {
var q = from c in this.context.Contracts
join p in this.context.Products
on c.ProductId equals p.Id
where ids.Contains(c.Id)
select p.Code;
//Adding .ConfigureAwait(false) fixes the problem here
var codes = await q.ToListAsync();
var slotCount = codes .Sum(p => char.GetNumericValue(p, p.Length - 1));
return Convert.ToInt32(slotCount);
}
但是,此方法(看起来与所有其他方法非常相似)不会导致死锁:
public async Task<List<CustomAccount>> SomeAccounts(IEnumerable<string> ids) {
return await this.context.Accounts
.Where(o => ids.Contains(o.Id))
.ToListAsync()
.ToCustomAccountListAsync();
}
我不太确定导致死锁的方法是什么。最终,他们都在做同样的查询数据库的任务。将ConfigureAwait(false) 添加到一种方法确实可以解决问题,但我不太确定它与其他执行良好的方法有什么区别。
编辑
为了简洁起见,我最初省略了一些附加代码:
public static Task<List<CustomAccount>> ToCustomAccountListAsync(this Task<List<Account>> sqlObjectsTask) {
var sqlObjects = sqlObjectsTask.Result;
var customObjects = sqlObjects.Select(o => PopulateCustomAccount(o)).ToList();
return Task.FromResult<List<CustomAccount>>(customObjects);
}
PopulateCustomAccount 方法只是从数据库Account 对象返回一个CustomAccount 对象。
【问题讨论】:
-
@MarcelN。 - 这个问题特别说要使用
await,正如我在开篇中所说的那样,我不能使用它。这个问题与您链接到的问题不同,因为我的问题仅出现在正在使用的许多特定Task中。我想知道导致问题的特定方法是什么,而其他方法都可以。 -
@MarcelN。 - 是的,我在所有任务中使用相同的上下文。实际上我最初使用的是
WhenAll,但这也陷入了僵局。该返回类型上没有Result属性。 -
我确定 Entity Framework 不支持在同一上下文中并行执行等待功能。事实上,它应该抛出一个异常。
-
@JustinHelgerson EF 并没有突然放弃并发支持。它从来不在那里。您以并发方式使用 EF 是无效的,必须修复。您寻求解释或解决方案吗?解决方案很简单:使用 ConfigureAsync。解释:我有预感。将
await Task.Delay(100);添加到 SomeAccounts 并查看它现在是否死锁。它应该。并发布 ToCustomAccountListAsync 的定义。
标签: c# asp.net asynchronous async-await deadlock