Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.ContinueWith from calling thread

I'm trying to execute the Func in ContinueWith from the thread that created the task (which is not GUI thread). I Tried this code:

SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

var scheduler = TaskScheduler.Current.FromCurrentSynchronizationContext();
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
var t = Task.Factory.StartNew(() =>
{
    Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
})
.ContinueWith(
    _ => Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId),
    // Specify where to execute the continuation
    scheduler
);

t.Wait();

But caller thread and .ContinueWith thread differs. Any idea why? I get the following result:

1 3 3

Looks like passing the scheduler causes ContinueWith to execute from the thread that is executing the actual Task, where I want it to be executed from the thread, which created the Task, in this case 1.

Thanks

like image 367
Davita Avatar asked Oct 29 '25 19:10

Davita


2 Answers

You can use TaskContinuationOptions.ExecuteSynchronously:

ContinueWith(() => { ... }, TaskContinuationOptions.ExecuteSynchronously);

ExecuteSynchronously tells it to try and run the continuation on whatever thread was last executing the antecedent task. And in the case of a continuation executing after a Task.Factory.StartNew call, that thread would be a thread pool thread.

But you have to note that this is merely a hint and the framework won't always honor your request. So you shouldn't structure your code so that running on the same thread becomes a necessity.

like image 191
mrahhal Avatar answered Nov 01 '25 09:11

mrahhal


SynchronizationContext class uses ThreadPool. If you need single thread synchronization context then you should use DispatcherSynchronizationContext, WindowsFormsSynchronizationContext or write your own synchronization context that will work according to your needs.

like image 36
nicolas2008 Avatar answered Nov 01 '25 08:11

nicolas2008



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!