通过与当前正在运行的框架 (SynchronizationContext) 关联的较低级别的调度程序来调度延续。
我觉得你有点混了。您可以使用给定的TaskScheduler
并在其上执行延续,而不是相反。这正是您分享的帖子中的这个片段所做的:
var ui = TaskScheduler.FromCurrentSynchronizationContext();
var tf = Task.Factory;
blendedImage.ContinueWith(_ =>
{
pictureBox1.Image = blendedImage.Result;
}, ui);
它告诉之前Task.ContinueWith
使用 UI TaskScheduler
(由调用提供TaskScheduler.FromCurrentSynchronizationContext()
)以便在特定上下文上调用延续,这次是 UI 消息循环。
如果你真的想深入了解细节,当你传递一个TaskScheduler
to时ContinueWith
,它最终会将它传递给一个名为的类,该类StandardTaskContinuation
具有以下Run
最终调用的方法TaskScheduler.InternalTaskQueue
:
internal void ScheduleAndStart(bool needsProtection)
{
if (needsProtection)
{
if (!this.MarkStarted())
{
return;
}
}
else
{
this.m_stateFlags |= 65536;
}
if (Task.s_asyncDebuggingEnabled)
{
Task.AddToActiveTasks(this);
}
if (AsyncCausalityTracer.LoggingOn &&
(this.Options & (TaskCreationOptions)512) == TaskCreationOptions.None)
{
AsyncCausalityTracer.TraceOperationCreation(
CausalityTraceLevel.Required, this.Id, "Task: " +
((Delegate)this.m_action).Method.Name, 0uL);
}
try
{
this.m_taskScheduler.InternalQueueTask(this);
}
catch (ThreadAbortException exceptionObject)
{
this.AddException(exceptionObject);
this.FinishThreadAbortedTask(true, false);
}
catch (Exception arg_93_0)
{
TaskSchedulerException ex = new TaskSchedulerException(arg_93_0);
this.AddException(ex);
this.Finish(false);
if ((this.Options & (TaskCreationOptions)512) == TaskCreationOptions.None)
{
this.m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
}
throw ex;
}
}