Catch an exception thrown by an async void method

前端 未结 6 1490
北恋
北恋 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 12:04

    Its also important to note that you will lose the chronological stack trace of the exception if you you have a void return type on an async method. I would recommend returning Task as follows. Going to make debugging a whole lot easier.

    public async Task DoFoo()
        {
            try
            {
                return await Foo();
            }
            catch (ProtocolException ex)
            {
                /* Exception with chronological stack trace */     
            }
        }
    

提交回复
热议问题