简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM