Should I worry about “This async method lacks 'await' operators and will run synchronously” warning

后端 未结 5 1132
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 01:18

I have a interface which exposes some async methods. More specifically it has methods defined which return either Task or Task. I am using the async/await keywords.

5条回答
  •  不知归路
    2020-11-30 01:23

    Note on exception behaviour when returning Task.FromResult

    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.
    

    (Cross post of my answer for When async Task required by interface, how to get return variable without compiler warning)

提交回复
热议问题