I'm digging into the async-await
mechanism and observed the throwing of a TaskCanceledException
that I can't explain yet.
In the sample below (self contained) I have the statement
await Task.Run(() => null);
I know that this statement on itself is useless but I isolated the issue, the real code has logic and returns null in some cases.
Why does this throw a TaskCanceledException
? If I return an arbitrary number (5 in the below example) it does not throw.
Furthermore if I await
the method the debugger of VS breaks but If I don't await
it then only a message is written to the output window of VS.
internal class Program
{
private static void Main(string[] args)
{
var testAsync = new TestAsync();
// Exception thrown but the debugger does not step in. Only a message is logged to the output window
testAsync.TestAsyncExceptionOnlyInTheOutputWindow();
// Exception thrown and the debugger breaks
testAsync.TestAsyncExceptionBreaksIntoTheDebugger();
Console.ReadKey();
}
}
internal class TestAsync
{
public async void TestAsyncExceptionOnlyInTheOutputWindow()
{
TestNullCase();
}
public async void TestAsyncExceptionBreaksIntoTheDebugger()
{
await TestNullCase();
}
private static async Task TestNullCase()
{
// This does not throw a TaskCanceledException
await Task.Run(() => 5);
// This does throw a TaskCanceledException
await Task.Run(() => null);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…