What is the best way to return a completed Task object?
It is possible to write Task.Delay(0), or Task.FromResult
But what is the
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