在文章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?
1条答案
按热度按时间s6fujrry1#
为什么
uiTaskScheduler == TaskScheduler.Current
返回false?方法
TaskScheduler.FromCurrentSynchronizationContext()
创建一个新的TaskScheduler示例。由于您调用了它两次,因此您将得到两个示例--尽管它们与同一SynchronizationContext相关联,但它们并不相等。将代码更改为: