Why can't I catch an exception from async code?

前端 未结 5 1881
南旧
南旧 2020-11-28 11:20

Everywhere I read it says the following code should work, but it doesn\'t.

public async Task DoSomething(int x)
{
   try
   {
      // Asynchronous implemen         


        
5条回答
  •  醉酒成梦
    2020-11-28 11:49

    As SLaks said, your code works fine.

    I strongly suspect you over-simplified your example, and have an async void in your code.

    The following works fine:

    private static void Main(string[] args)
    {
        CallAsync();
        Console.Read();
    }
    
    public static async void CallAsync()
    {
        try
        {
            await DoSomething();
        }
        catch (Exception)
        {
            // Handle exceptions ?
            Console.WriteLine("In the catch");
        }
    }
    
    public static Task DoSomething()
    {
        return Task.Run(() =>
        {
            throw new Exception();
        });
    }
    

    The following doesn't work:

    private static void Main(string[] args)
    {
        CallAsync();
        Console.Read();
    }
    
    public static void CallAsync()
    {
        try
        {
            DoSomething();
        }
        catch (Exception)
        {
            // Handle exceptions ?
            Console.WriteLine("In the catch");
        }
    }
    
    public static async void DoSomething()
    {
        await Task.Run(() =>
        {
            throw new Exception();
        });
    }
    

    See http://msdn.microsoft.com/en-us/magazine/jj991977.aspx

    Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Figure 2 illustrates that exceptions thrown from async void methods can’t be caught naturally.

提交回复
热议问题