【问题标题】:TaskScheduler - executing continuationsTaskScheduler - 执行延续
【发布时间】:2016-02-21 10:06:27
【问题描述】:

在阅读了一些关于TaskScheduler (good article here) 之后,发现TaskScheduler 可以:

  1. 调度任务 - 通过使用QueueTask 方法,在上面的示例中只是将Posts 任务执行到选定的SynchronizationContext

  2. 通过与当前运行的框架 (SynchronizationContext) 关联的较低级别的调度程序来调度继续。

2. 是否与TaskCotninueWith 方法有任何关系?我显然理解 1.,但看不到 2. 对于TaskScheduler 是如何正确的。以TaskScheduler的什么方式会发生这种情况?

【问题讨论】:

  • 嗯,有Task.ContinueWith 重载采取 TaskScheduler,以便由该调度程序安排继续......你在想什么?

标签: c# multithreading synchronizationcontext taskscheduler


【解决方案1】:

通过关联的低级调度程序调度延续 与当前运行的框架(SynchronizationContext)。

我觉得你有点搞混了。您可以使用给定的TaskScheduler 并在其上执行延续,而不是相反。这正是您分享的帖子中的 sn-p 所做的:

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

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 2016-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2011-01-25
    • 2018-02-25
    相关资源
    最近更新 更多