How can I make VS break on exceptions in an async Task, without breaking on all exceptions?

前端 未结 5 692
小蘑菇
小蘑菇 2021-02-01 15:06

As indicated here and here, exceptions occuring in an async Task are technically not unhandled.

This is particularly nasty when working with MVC. It actually took us a w

5条回答
  •  醉梦人生
    2021-02-01 15:27

    The try-catch reference in MSDN has some guidance and examples on exceptions in async methods, and states: "The completed task to which await is applied might be in a faulted state because of an unhandled exception in the method that returns the task. Awaiting the task throws an exception."

    For the example given on that page, it states: "The following example illustrates exception handling for async methods. To catch an exception that an async task throws, place the await expression in a try block, and catch the exception in a catch block. Uncomment the throw new Exception line in the example to demonstrate exception handling. The task's IsFaulted property is set to True, the task's Exception.InnerException property is set to the exception, and the exception is caught in the catch block."

    Here's the copy from the example given there:

    public async Task DoSomethingAsync()
    {
        Task theTask = DelayAsync();
    
        try
        {
            string result = await theTask;
            Debug.WriteLine("Result: " + result);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Exception Message: " + ex.Message);
        }
        Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled);
        Debug.WriteLine("Task IsFaulted:  " + theTask.IsFaulted);
        if (theTask.Exception != null)
        {
            Debug.WriteLine("Task Exception Message: "
                + theTask.Exception.Message);
            Debug.WriteLine("Task Inner Exception Message: "
                + theTask.Exception.InnerException.Message);
        }
    }
    
    private async Task DelayAsync()
    {
        await Task.Delay(100);
    
        // Uncomment each of the following lines to 
        // demonstrate exception handling. 
    
        //throw new OperationCanceledException("canceled");
        //throw new Exception("Something happened.");
        return "Done";
    }
    
    // Output when no exception is thrown in the awaited method: 
    //   Result: Done 
    //   Task IsCanceled: False 
    //   Task IsFaulted:  False 
    
    // Output when an Exception is thrown in the awaited method: 
    //   Exception Message: Something happened. 
    //   Task IsCanceled: False 
    //   Task IsFaulted:  True 
    //   Task Exception Message: One or more errors occurred. 
    //   Task Inner Exception Message: Something happened. 
    
    // Output when a OperationCanceledException or TaskCanceledException 
    // is thrown in the awaited method: 
    //   Exception Message: canceled 
    //   Task IsCanceled: True 
    //   Task IsFaulted:  False
    

提交回复
热议问题