编程语言
首页 > 编程语言> > c# – TaskScheduler – 执行continuation

c# – TaskScheduler – 执行continuation

作者:互联网

在阅读了有关TaskScheduler(good article here)的一些内容后,发现TaskScheduler可以:

>计划任务 – 使用QueueTask方法,在上面的示例中,只将Posts任务执行发布到选定的SynchronizationContext
>通过与当前运行的框架(SynchronizationContext)关联的低级调度程序安排延续.

2.以任何方式与CotninueWith任务方法有关吗?我很明白1.但是不知道2.对于TaskScheduler来说是如何. TaskScheduler会采用什么方法?

解决方法:

Schedule continuations through the lower-level scheduler associated
with the currently running framework (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传递给ContinueWith时,它最终将它传递给一个名为StandardTaskContinuation的类,该类具有以下Run方法,最终调用TaskScheduler.InternalTask​​Queue:

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;
    }
}

标签:c,multithreading,taskscheduler,synchronizationcontext
来源: https://codeday.me/bug/20190623/1271455.html