C# Async Task Method Without Await or Return

前端 未结 2 366
挽巷
挽巷 2021-01-04 04:51

I have an Interface I that is implemented in two places like:

interface I 
{ 
   Task DoSomething();
}

The interface has async Task DoSomet

2条回答
  •  滥情空心
    2021-01-04 05:22

    I see that most people prefer to leave out the async and use Task.ComletedTask instead. But even if await is not used, there is still a big difference in exception handling

    Consider the following example

    static async Task Main(string[] args)
    {
    
        Task task = test(); // Will throw exception here
        await task;
    
        Task taskAsync = testWithAsync();
        await taskAsync; // Will throw exception here
    }
    
    static Task test()
    {
        throw new Exception();
        return Task.CompletedTask; //Unreachable, but left in for the example
    }
    
    static async Task testWithAsync()
    {
        throw new Exception();
    }
    

    Using

    test().ContinueWith(...); or Task.WhenAll(test())

    may result in unexpected behaviour.

    Therefore, I prefer async instead of Task.CompletedTask or Task.FromResult.

提交回复
热议问题