task-parallel-libraryasync-await

How is it possible to have a Task that RanToCompletion but also Result.Status is Faulted?


I have this strange situation at the moment. I have a Task within which I am throwing an exception. The TaskScheduler.UnobservedTaskException event fires but the UnobservedException is never rethrown (even with ThrowUnobservedTaskExceptions enabled="true"). When I check in the debugger I see the Task looks like so:

RanToCompletion but also Status Faulted

This seems suspicious to me. How can it have RanToCompletition but also have a Faulted Result? The exception inside the result is the one I'm throwing, but it's not making it to the Task.Exception property.


Solution

  • This looks like you have a Task<Task>. The outer Task ran to completion and its Result is another Task, this time a faulted one.

    That's exactly what the debugger shows: the “Result” line is not some special line containing summary of the whole object, it's the Result property.

    Without seeing your code, it's hard to say how the Task<Task> was created. But a relatively common situation in C# 5.0 is if you run an async method using Task.Factory.StartNew(). If that's the case, you should either call the async method directly, or, if you want to run it on a background thread, use Task.Run(), which automatically unwraps the Task<Task> into a simple Task.