StackExchange.Redis Deadlocking

徘徊边缘 提交于 2019-12-01 04:10:55
Marc Gravell

Here we go:

return Cache.UseCache1().Result

boom; deadlock. But nothing to do with StackExchange.Redis.

At least, from most sync-context providers. This is because your awaits are all implicitly requesting sync-context activation - which can mean "on the UI thread" (winforms, WPF), or "on the currently designated worker thread" (WCF, ASP.NET, MVC, etc). The problem here is that this thread will never be available to process those items, because .Result is a synchronous and blocking call. Thus none of your completion callbacks will get processed, because the only thread that can possibly process them is waiting for them to finish before making itself available.

Note: StackExchange.Redis does not use the sync-context; it explicitly disconnects from sync-context to avoid being the cause of deadlocks (this is normal and recommended for libraries). The key point is that your code doesn't.

Options:

  • don't mix async and .Result / .Wait(), or
  • have all of your await calls (or at least those underneath .UseCache1()) explicitly call .ConfigureAwait(false) - note, however, that this means that the completions will not occur in the calling context!

The first option is the simplest; if you can isolate a tree of calls that do not depend on sync-context then the second approach is viable.

This is a very common problem; I did pretty much the same thing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!