wpf 何时是TaskScheduler,当前的UI TaskScheduler?

7cwmlq89  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(113)

在文章here中,Stephen描述了在外部StartNew(参见下面的代码片段)中,TaskScheduler.Current是我们的UI任务调度器。实际上,下面代码的输出似乎表明所有操作都在UI线程上执行。然而,当我试图证实这一点时,我得到了一个不同的答案:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    var ui = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
    ui.StartNew(() =>
    {
        Debug.WriteLine("TaskScheduler.Current == UI TaskScheduler: " + (uiTaskScheduler == TaskScheduler.Current));
        Debug.WriteLine("UI on thread " + Environment.CurrentManagedThreadId);
        Task.Factory.StartNew(() =>
        {
            Debug.WriteLine("Background work on thread " + Environment.CurrentManagedThreadId);
        });
    });
}

和输出:

TaskScheduler.Current == UI TaskScheduler: False
UI on thread 1
Background work on thread 1

为什么uiTaskScheduler == TaskScheduler.Current返回false?

s6fujrry

s6fujrry1#

为什么uiTaskScheduler == TaskScheduler.Current返回false?
方法TaskScheduler.FromCurrentSynchronizationContext()创建一个新的TaskScheduler示例。由于您调用了它两次,因此您将得到两个示例--尽管它们与同一SynchronizationContext相关联,但它们并不相等。
将代码更改为:

var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var ui = new TaskFactory(uiTaskScheduler);
...

相关问题