为什么带有ToListAsync的EF查询会在WPF应用程序中挂

为什么带有ToListAsync的EF查询会在WPF应用程序中挂

本文介绍了为什么带有ToListAsync的EF查询会在WPF应用程序中挂起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是查询:

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 ,它可以正常运行,但会挂起.我怀疑某种线程问题.该查询是在我的视图模型的 InitializeAsync 方法期间调用的,该方法是从视图中的事件"调用的:

If I replace ToListAsync with ToList, it runs fine, but otherwise it hangs. I suspect some sort of threading issue. The query is called during my viewmodel's InitializeAsync method, which is called from an 'event' in the view:

public override async void OnNavigatedTo(NavigationContext navigationContext)
{
    await InitializeModelAsync(InitModelCts.Token);
}

这是 INavigationAware 的视图实现的一部分.

This is part of the view's implementation of INavigationAware.

推荐答案

如果您不通过调用 ConfigureAwait 方法来捕获上下文,是否可行?:

Does it work if you don't capture the context by calling the ConfigureAwait method?:

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;
}

还请注意,最初的Entity Framework设置并非真正异步:

Also note the initial Entity Framework setup is not really asynchronous:

EF6 ToListAsync冻结Winforms

...所以您可能希望将整个查询和上下文创建工作卸载到后台线程:

...so you might want to offload the entire query and context creation to a background thread:

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;
    }
});

这篇关于为什么带有ToListAsync的EF查询会在WPF应用程序中挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 00:26