So here is what I'm trying to achieve. I launch a task and don't do wait/result on it. To ensure that if launched task goes to faulted state (for e.g. say throw an exception) I crash the process by calling Environment FailFast in Continuation.
How the problem I'm facing is that If I ran below code, Inside ContinueWith, the status of the task (which threw exception) shows up as "RanToCompletion". I expected it to be Faulted State.
private Task KickOfTaskWorkAsync()
{
var createdTask = Task.Run(() => this.RunTestTaskAsync(CancellationToken.None).ConfigureAwait(false), CancellationToken.None);
createdTask.ContinueWith(
task => Console.WriteLine("Task State In Continue with => {0}", task.Status));
return createdTask;
}
private async Task RunTestTaskAsync(CancellationToken cancellationToken)
{
throw new Exception("CrashingRoutine: Crashing by Design");
}
This is really strange :( If I remove the 'ConfigureAwait(false)' inside Task.Run function call, the task does goes to Faulted state inside Continue with. Really at loss to explain what's going on and would appreciate some help from community.
[Update]: My colleague pointed out an obvious error. I am using ConfigureAwait while I make a call to RunTestAsync inside Test.Run even though I don't await it. In this case, ConfigureAwait doesn't return a Task to Task.Run. If I don't call ConfigureAwait, a Task does get returned and things work as expected.
ContinueWith
?ContinueWith
was for the pre-async-await era; now you can just useawait RunTestTaskAsync()
followed byConsole.WriteLine()
and catch any exceptions you want in the more standard way; i.e.try
..catch
. – sellotapeawait
is a more idiomatic way to deal with continuations now. However, the OP would still have the same issue even usingawait
. They would be awaiting the wrongTask
object and would still see the task in a non-faulted state. – Peter DunihocreatedTask
, then yes, but if he just awaitsRunTestTaskAsync()
(which there seems little reason not to, but I guess there's not enough context to be sure) thecatch
will catch the exception he throws. – sellotapeawait
doesn't address his question at all. IfContinueWith()
is replaced withawait
here, the same issue will still happen. The question would just have slightly reworded code. – Peter Dunihoawait RunTestTaskAsync()
in the first comment. – sellotape