How to correctly rethrow an exception of task already in faulted state?

.net, async-await, c#, task-parallel-library

Solution

To properly re-throw an exception, you should use `ExceptionDispatchInfo`:

ExceptionDispatchInfo.Capture(task.Exception.InnerException).Throw();

You can also do:

task.GetAwaiter().GetResult();

P.S. Your `Action` approach will not work correctly, since you're creating an `async void` method, and you cannot catch exceptions propagated from that method.

Problem

I have a synchronous method which, amongst other things, checks the status of a pending task and rethrows its exception, if any: ``` void Test(Task task) { // ... if (task.IsFaulted) throw task.Exception; // ... } ``` This doesn't propagate the exception stack trace information and is debugger-unfriendly. Now, if the `Test` was `async`, it would not be as simple and natural as this: ``` async Task Test(Task task) { // ... if (task.IsFaulted) await task; // rethrow immediately and correctly // ... } ``` Question: how to do it right for a synchronous method? I have come up with this but I do not like it: ``` void Test(Task task) { // ... if (task.IsFaulted) new Action(async () => await task)(); // ... } ```

Original source