What is the best way to return completed Task?

后端 未结 3 1618
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 05:52

What is the best way to return a completed Task object?

It is possible to write Task.Delay(0), or Task.FromResult(true) whatever.

But what is the

3条回答
  •  半阙折子戏
    2021-01-29 06:50

    Here's a little demo which shows the difference in exception handling between methods marked and not marked with async.

    public Task GetToken1WithoutAsync() => throw new Exception("Ex1!");
    
    // Warning: This async method lacks 'await' operators and will run synchronously. Consider ...
    public async Task GetToken2WithAsync() => throw new Exception("Ex2!");  
    
    public string GetToken3Throws() => throw new Exception("Ex3!");
    public async Task GetToken3WithAsync() => await Task.Run(GetToken3Throws);
    
    public async Task GetToken4WithAsync() { throw new Exception("Ex4!"); return await Task.FromResult("X");} 
    
    
    public static async Task Main(string[] args)
    {
        var p = new Program();
    
        try { var task1 = p.GetToken1WithoutAsync(); } 
        catch( Exception ) { Console.WriteLine("Throws before await.");};
    
        var task2 = p.GetToken2WithAsync(); // Does not throw;
        try { var token2 = await task2; } 
        catch( Exception ) { Console.WriteLine("Throws on await.");};
    
        var task3 = p.GetToken3WithAsync(); // Does not throw;
        try { var token3 = await task3; } 
        catch( Exception ) { Console.WriteLine("Throws on await.");};
    
        var task4 = p.GetToken4WithAsync(); // Does not throw;
        try { var token4 = await task4; } 
        catch( Exception ) { Console.WriteLine("Throws on await.");};
    }
    
    // .NETCoreApp,Version=v3.0
    Throws before await.
    Throws on await.
    Throws on await.
    Throws on await.
    

    Moved (and edited) from When async Task required by interface, how to get return variable without compiler warning)

提交回复
热议问题