这是查询:
using (var db = new AppDbContext())
{
var items = await db.Branches
.Where(b => b.OrgId == orgId)
.Select(t => new SelectListItem<int> {Key = t.Id, Value = t.Name})
.ToListAsync();
return items;
}
如果我将ToListAsync
替换为ToList
,它运行正常,但否则会挂起。我怀疑某种线程问题。在我的viewmodel的InitializeAsync
方法中调用该查询,该方法是从视图中的“事件”调用的:
public override async void OnNavigatedTo(NavigationContext navigationContext)
{
await InitializeModelAsync(InitModelCts.Token);
}
这是视图实现INavigationAware
。
答案 0 :(得分:1)
如果您不通过调用ConfigureAwait
方法捕获上下文,是否有效?:
using (var db = new AppDbContext())
{
var items = await db.Branches
.Where(b => b.OrgId == orgId)
.Select(t => new SelectListItem<int> { Key = t.Id, Value = t.Name })
.ToListAsync().ConfigureAwait(false);
return items;
}
另请注意,初始实体框架设置并非真正异步:
EF6 ToListAsync freezes Winforms
...所以您可能希望将整个查询和上下文创建卸载到后台线程:
await Task.Run(()=>
{
using (var db = new AppDbContext())
{
var items = db.Branches
.Where(b => b.OrgId == orgId)
.Select(t => new SelectListItem<int> { Key = t.Id, Value = t.Name })
.ToList();
return items;
}
});