Exception in async methods is not caught

前端 未结 2 1819
面向向阳花
面向向阳花 2021-01-27 11:48

The following code does not catch my OperationCancelException which is thrown by calling ct.ThrowIfCancellationRequested.

public partial class Title         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 12:29

    In your first example the exception is not caught because it does not occure before leaving the try/catch block. If you want to catch it there you need to wait/await it there exactly like you do in the second example. If you do not await the returned task the method continues execution and leaves the try/catch block before the exception actually occures...

    If you want to catch the exception "out of band" you can also register to TaskScheduler.UnobservedTaskException (this event is called if a task is throwing an exception which is nowhere caught) to get all uncaught exceptions or monitor the tasks Exception property. May also check out THIS answer.

提交回复
热议问题