StackExchange.Redis Deadlocking

前端 未结 1 1873
一生所求
一生所求 2021-01-12 12:56

I\'m using StackExchange.Redis (SE.R henceforth) in my Nancy application. There is a single global ConnectionMultiplexer that gets automatically pa

相关标签:
1条回答
  • 2021-01-12 13:42

    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.

    0 讨论(0)
提交回复
热议问题