C#/.NET 4.5 - Why does “await Task.WhenAny” never return when provided with a Task.Delay in a WPF application's UI thread?

后端 未结 1 1655
慢半拍i
慢半拍i 2021-01-06 04:36

Given the following code, why does Task.WhenAny never return when provided with a Task.Delay of 1 second? Technically I\'m not sure if it does return after a extended amount

相关标签:
1条回答
  • 2021-01-06 04:45

    I predict that further up your call stack, you're calling Task.Wait or Task<T>.Result. This will cause a deadlock that I explain in full on my blog.

    In short, what happens is that await will (by default) capture the current "context" and use that to resume its async method. In this example, the "context" is the WPF UI context.

    So, when your code does its await on the task returned by WhenAll, it captures the WPF UI context. Later, when that task completes, it will attempt to resume on the UI thread. However, if the UI thread is blocked (i.e., in a call to Wait or Result), then the async method cannot continue running and will never complete the task it returned.

    The proper solution is to use await instead of Wait or Result. This means your calling code will need to be async, and it will propagate through your code base. Eventually, you'll need to decide how to make your UI asynchronous, which is an art in itself. At least to start with, you'll need an async void event handler or some kind of an asynchronous MVVM command (I explore async MVVM commands in an MSDN article). From there you'll need to design a proper asynchronous UI; i.e., how your UI looks and what actions it permits when asynchronous operations are in progress.

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