Task.Wait doesn't propagate exception
See original GitHub issueusing System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp14
{
class Program
{
static void Main(string[] args)
{
try
{
var cts = new CancellationTokenSource();
var task = Task.Run(
async () =>
{
await Task.Delay(TimeSpan.FromSeconds(10), cts.Token);
},
cts.Token);
cts.CancelAfter(TimeSpan.FromSeconds(1));
task.Wait();
// .NET 2.0 - 3.5 reach this line
Console.WriteLine("Must not get there");
}
catch (AggregateException)
{
Console.WriteLine("Expected");
}
}
}
}
I guess related to #120
Issue Analytics
- State:
- Created 3 years ago
- Comments:9 (5 by maintainers)
Top Results From Across the Web
c# - Wait for async Task without wrapping exceptions in ...
I am going to use these in a command line application. So I need to call them synchronously a lot. No, you don't....
Read more >Exception handling (Task Parallel Library)
Exceptions are propagated when you use one of the static or instance Task.Wait methods, and you handle them by enclosing the call in...
Read more >Why exceptions in async methods are “dangerous” in C# | ...
No exception was thrown because the MyAsyncMethod routine is not awaited and the exception is literally lost with the Task.
Read more >Bug - async and uncaught Exceptions
Hello everyone, In one of the projects I'm working on, we're using async and await in order to execute code asynchronously.
Read more >Propagating multiple async exceptions (or not)
If the task throws an AggregateException when we wait for it, that exception is propagated to the generated code responsible for the async ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Trying the code above in .NET 2.0 throws an AggregateException with TaskCanceledException with a CancellationToken with IsCancellationRequested = true. While the same code in LinqPad has IsCancellationRequested = false.
I can also confirm that Unwrap should copy the CancellationToken.
Edit: that is a total of 3 things to fix:
This happens: The
Task
gets marked cancelled, but theCancellationToken
on theTask
says that no cancellation was requested. Why? Because the task has aCancellationToken
from the default source. Why? BecauseTask.Run
usesUnwrap
andUnwrap
does not copy theCancellationToken
. I’ll fix that.