Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuation Task in the same thread as previous

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.

like image 614
Luis Filipe Avatar asked Dec 27 '12 16:12

Luis Filipe


People also ask

What is a continuation task?

A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.

Which code creates a chain of task to be executed after one another?

c# - Run sequence of tasks, one after the other - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What does calling task ContinueWith () do?

ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.

Are tasks and threads the same?

Differences Between Task And ThreadThe Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.


1 Answers

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.

like image 184
usr Avatar answered Oct 19 '22 06:10

usr