Why doesn't this exception get thrown?

前端 未结 3 1851
醉话见心
醉话见心 2020-12-10 16:26

I use a set of tasks at times, and in order to make sure they are all awaited I use this approach:

public async Task ReleaseAsync(params Task[] TaskArray)
{
         


        
3条回答
  •  有刺的猬
    2020-12-10 16:44

    TL;DR: run() throws the exception, but you're awaiting WhenAny(), which doesn't throw an exception itself.


    The MSDN documentation for WhenAny states:

    The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state.

    Essentially what is happening is that the task returned by WhenAny simply swallows the faulted task. It only cares about the fact that the task is finished, not that it has successfully completed. When you await the task, it simply completes without error, because it is the internal task that has faulted, and not the one you're awaiting.

提交回复
热议问题