Task.ContinueWith() executing but Task Status is still "Running"

asked6 years ago
last updated6 years ago
viewed2.6k times
Up Vote18Down Vote

Consider the following code:

MyTask = LongRunningMethod(progressReporter, CancelSource.Token)
    .ContinueWith(e => 
        { Log.Info("OnlyOnCanceled"); }, 
        default, 
        TaskContinuationOptions.OnlyOnCanceled,
        TaskScheduler.FromCurrentSynchronizationContext())
    .ContinueWith(e => 
        { Log.Info("OnlyOnFaulted"); }, 
        default, 
        TaskContinuationOptions.OnlyOnFaulted,
        TaskScheduler.FromCurrentSynchronizationContext())
    .ContinueWith(e => 
        { Log.Info("OnlyOnRanToCompletion"); }, 
        default,
        TaskContinuationOptions.OnlyOnRanToCompletion, 
        TaskScheduler.FromCurrentSynchronizationContext())
    .ContinueWith(e => 
        { Log.Info("None"); }, 
        default, 
        TaskContinuationOptions.None,
        TaskScheduler.FromCurrentSynchronizationContext());
  • When I cancel the task using the provided CancelSource, output is: OnlyOnCanceled None as expected.- When LongRunningMethod throws an Exception output is: OnlyOnFaulted None as expected.- When LongRunningMethod completes output is: None so the ContinueWith with TaskContinuationOptions.OnlyOnRanToCompletion is not executed as I would expect.

I checked MyTask.Status in the last ContinueWith branch and it is still Running. So with that in mind, I would expect OnlyOnRanToCompletion to be skipped. The question is, why is the Status still Running? Looking at the debug output, I can see that LongRunningMethod ran to the end.