Continuation Task in the same thread as previous

Luis Filipe picture Luis Filipe · Dec 27, 2012 · Viewed 10.4k times · Source

I have an WebService that creates a task and a continuation task.

In the first task we set Thread.CurrentPrincipal

Hence, When the ContinuationTask starts it no longer has the Thread.CurrentPrincipal.

I'd like to specify in the ContinuationTask that it should run in the same thread as its antecedent.

I've searched the web but i only found the requirement for the thread to run in the SynchronizationContext, therefore i am starting to think I am missing some basic rule, specially regarding how Thread.Principal should work.

Answer

usr picture usr · Dec 27, 2012

First of all, don't use TaskContinuationOptions.ExecuteSynchronously for this purpose! You can't force the continuation on the same thread. It only works with very high probability. There are always cases where it does not work: Too much recursion will cause the TPL not to execute synchronously. Custom TaskSchedulers are also not obliged to support this.

This is a common misconception, especially because it is being wrongly propagated on the web. Here is some reading on that topic: http://blogs.msdn.com/b/pfxteam/archive/2012/02/07/10265067.aspx

If you need to run on the same thread, do this:

Task.Factory.StartNew(() => { First(); Second(); });

So easy.

Let me illustrate why that works by showing an alternative solution:

void MyCompositeTask()
{
  var result = First();
  Second(result);
}
Task.Factory.StartNew(() => MyCompositeTask());

This looks more intuitive: We pass MyCompositeTask to the TPL to run. The TPL does not care what we do in our callback. We can do whatever we want, including calling multiple methods and passing the results.