ToListAsync()完全没有完成 [英] ToListAsync() does not complete at all

查看:1062
本文介绍了ToListAsync()完全没有完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一些查询异步。
但是当我调试代码时,大多数时候调用ToListAsync()时,程序停止。
没有可见的异常,并且清除了callstack窗口。
当我按下VS中的暂停按钮时,我可以在调用当前方法之前看到堆栈框架。

I want to execute some queries async. But when I debug through the code, most times when an ToListAsync() is called the program stops. There is no visible exception, and the callstack window is cleared. When I press the pause button in VS, I can see the stack frame just before the current method was called.

var res1 = await context.Address().Where(...).ToListAsync();
var res2 = await context.Person().Where(...).ToListAsync();
var res3 = await context.Rule().Where(...).ToListAsync();

有时第一个电话工作,在极少数情况下也是第二个。
但是至少在第三个调用程序停止。
我绝对不知道为什么...

Sometimes the first call works, in rare cases the second too. But at least at the third call the program stops. I have absolutely no clue why...

推荐答案

从评论中:


它是一个wpf应用程序。这些命令在异步方法之内。我使用 var result = LoadAsync.Result();


$ b从非异步方法中调用$ b

在那里,这是一个死锁 DispatcherSynchronizationContext 尝试将继续(第一个等待之后的所有内容)返回到调度器(UI)线程上,这是目前阻止调用 LoadAsync.Result

Right there, thats a deadlock. The DispatcherSynchronizationContext tries to marshal the continuation (everything after the first await) back onto the dispatcher (UI) thread, which is currently blocked by the call to LoadAsync.Result

解决方案:

等待 / code>而不是使用 Task.Result

  1. await at the top of your call stack by making your method return an async Task instead of using Task.Result:

await LoadAsync();


  • 如果绝对不能将堆栈顶部的方法更改为 async Task ,而对于某些晦涩的原因,还必须调用 Task.Result ,使用 ConfigureAwait(false) 当你的内部异步方法。这将告诉同步上下文显式地不会将工作组织回调度程序线程:

  • If you absolutely cant change the method at the top of of the stack to async Task and for some obscure reason have to still call Task.Result, use ConfigureAwait(false) when awating your inner async methods. This will tell the sync context to explicitly not attempt to marshal work back to the dispatcher thread:

    var res1 = await context.Address().Where(...).ToListAsync().ConfigureAwait(false);
    var res2 = await context.Person().Where(...).ToListAsync().ConfigureAwait(false);
    var res3 = await context.Rule().Where(...).ToListAsync().ConfigureAwait(false);        
    


  • 这篇关于ToListAsync()完全没有完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆