Jack Ukleja
Jack Ukleja

Reputation: 13521

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.

Upvotes: 2

Views: 1425

Answers (2)

Ohad Bitton
Ohad Bitton

Reputation: 515

This is probably coming from a call to Task.Factory.StartNew() with some async method. The right solution is to not pass it an async method, if you cant, you can use a lambda and wait in the lambda.

Regardless, if you want to await on an inner task you could unwrap it:

var task = Task.Factory.StartNew(workAsync).Unwrap().
await task

Upvotes: 0

svick
svick

Reputation: 244948

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.

Upvotes: 4

Related Questions