Exception handling outside of Task

前端 未结 2 1279
余生分开走
余生分开走 2021-01-16 02:50

Just noticed strange thing: to catch exception in caller from new Task, lambda MUST be marked as async!? Is it really necessary even if delegate has no await operators at al

相关标签:
2条回答
  • 2021-01-16 03:33

    When using async/await, exceptions are automatically unwrapped at the site of the await. When using a Task and .Wait(), any exception are wrapped when they come out of the Task, and thus getting information requires you to dig into the Task.Exception property, since they do not propagate up the call stack.

    See https://dotnetfiddle.net/MmEXsT

    0 讨论(0)
  • 2021-01-16 03:51

    Methods that return Task - such as Task.Run or async methods - will place any exceptions on that returned Task. It's up to you to observe that exception somehow. Normally this is done with await, like this:

    await Task.Run(() => { throw ... });
    

    In your case, the problem is in this line:

    result = OnSomeEvent((s, ea) => RunSomeTask());
    

    In this code, RunSomeTask is returning a Task, and that Task is never awaited. In order to observe the exception, you should await that task.

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