Catch an exception thrown by an async void method

前端 未结 6 1553
北恋
北恋 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:51

    The exception can be caught in the async function.

    public async void Foo()
    {
        try
        {
            var x = await DoSomethingAsync();
            /* Handle the result, but sometimes an exception might be thrown
               For example, DoSomethingAsync get's data from the network
               and the data is invalid... a ProtocolException might be thrown */
        }
        catch (ProtocolException ex)
        {
              /* The exception will be caught here */
        }
    }
    
    public void DoFoo()
    {
        Foo();
    }
    

提交回复
热议问题