Handling exceptions from the synchronous part of async method

后端 未结 2 427
一个人的身影
一个人的身影 2021-01-13 03:05

I\'m dealing with the situation where the task I start may throw, while still executing synchronously on the initial thread. Something like this, for illustrative purposes:

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 03:28

    I'd split it into two parts, rather than relying on task.GetAwaiter().GetResult() to work. I'd be afraid that someone maintaining TestAsync could unwittingly break things in the future.

    This is how I would write it. This should preserve the behavior you've got, but I find it more obvious what's going on:

    static Task Test()
    {
        var random = new Random(Environment.TickCount).Next();
        if (random % 2 != 0)
            throw new ApplicationException("1st");
    
        return TestAsync();
    }
    
    static async Task TestAsync()
    {
        await Task.Delay(2000);
        Console.WriteLine("after await Task.Delay");
        throw new ApplicationException("2nd");
    }
    
    
    
    static void Main(string[] args)
    {
        try
        {
            Test();
            Console.WriteLine("TestAsync continues asynchronously...");
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
    
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();
    }
    

提交回复
热议问题