Task.ContinueWith 从调用线程

Dav*_*ita 3 c# multithreading asynchronous task-parallel-library

我试图从创建任务的线程(不是 GUI 线程)执行ContinueWith 中的Func。我试过这个代码:

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();
Run Code Online (Sandbox Code Playgroud)

但调用者线程和 .ContinueWith 线程有所不同。知道为什么吗?我得到以下结果:

1 3 3

看起来传递调度程序会导致ContinueWith从正在执行实际任务的线程执行,我希望它从创建任务的线程执行,在本例中为1。

谢谢

mra*_*hal 5

您可以使用TaskContinuationOptions.ExecuteSynchronously

ContinueWith(() => { ... }, TaskContinuationOptions.ExecuteSynchronously);
Run Code Online (Sandbox Code Playgroud)

ExecuteSynchronously告诉它尝试最后执行先行任务的任何线程上运行延续。在调用后执行延续的情况下Task.Factory.StartNew,该线程将是线程池线程。

但您必须注意,这只是一个提示,框架并不总是满足您的请求。因此,您不应该构建代码以使在同一线程上运行成为必要。