Continuation of tasks is always performed even when TaskContinuationOptions is specified.

I want to run some code when the async task completes successfully.

From reading the documentation and examples on the Internet, I thought I could use Task.ContinueWith and specify TaskContinuationOptions.OnlyOnRanToCompletion .

However, this does not behave as I expected.

The following code is a console program created in Visual Studio 2012, .NET 4.5:

 using System; using System.Threading.Tasks; namespace TaskContinueTest { class Program { static void Main(string[] args) { var jobTask = Task.Factory.StartNew(() => { }); jobTask.ContinueWith((task, options) => { Console.WriteLine("Completed handler. Task status is {0}", task.Status); }, TaskContinuationOptions.OnlyOnRanToCompletion); jobTask.ContinueWith((task, options) => { Console.WriteLine("Faulted handler. Task status is {0}", task.Status); }, TaskContinuationOptions.OnlyOnFaulted); Console.ReadLine(); } } } 

when I start, I get the output:

 Completed handler. Task status is RanToCompletion Faulted handler. Task status is RanToCompletion 

which is very surprising (at least for me). Why are both sequels planned?

I get the same behavior if I throw an exception in jobTask , but now the output is:

 Completed handler. Task status is Faulted Faulted handler. Task status is Faulted 

So, the structure clearly knows the status of the task, but why are both sequels still planned?

+4
source share
1 answer

I think the problem is that you accidentally cause this overload

 public Task ContinueWith( Action<Task, Object> continuationAction, Object state ) 

Do you want this overload :

 public Task ContinueWith( Action<Task> continuationAction, TaskContinuationOptions continuationOptions ) 

You just need to modify your lambda expressions to use one parameter:

 Task.ContinueWith(task => Console.WriteLine(...), TaskContinuationOptions.OnlyOnRanToCompletion); 
+4
source

All Articles