Exception in async methods is not caught

前端 未结 2 1820
面向向阳花
面向向阳花 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.

    0 讨论(0)
  • 2021-01-27 12:37

    Exeption is thrown in the task on another thread.

    public async Task GetCancelExceptionAsync(CancellationToken ct)
            {
                try
                {
                    await Task.Delay(1000);
                    ct.ThrowIfCancellationRequested();
                }
                catch (Exception e)
                {
                    // your Cancleation expeption
                }
            }
    
    0 讨论(0)
提交回复
热议问题