Catch an exception thrown by an async void method

前端 未结 6 1496
北恋
北恋 2020-11-22 11:20

Using the async CTP from Microsoft for .NET, is it possible to catch an exception thrown by an async method in the calling method?

public async void Foo()
{
         


        
6条回答
  •  长发绾君心
    2020-11-22 11:45

    The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.

    This opens up a simpler solution if you can change the method signatures - alter Foo() so that it returns type Task and then DoFoo() can await Foo(), as in this code:

    public async Task Foo() {
        var x = await DoSomethingThatThrows();
    }
    
    public async void DoFoo() {
        try {
            await Foo();
        } catch (ProtocolException ex) {
            // This will catch exceptions from DoSomethingThatThrows
        }
    }
    

提交回复
热议问题