【发布时间】:2014-03-05 10:36:50
【问题描述】:
不太清楚这里发生了什么 -
这段代码会导致问题,因为它首先从主线程调用(在 VS 的任务视图中验证)并调度任务,但是当在 UpdateSearchCache 中设置断点时,我们现在处于工作线程中 -不再是主要的!
从那里调用的后续 UI 代码在工作线程上执行时会失败。
这不是指定调度程序的重点吗?我错过了什么?
启动我们的应用程序时会调用此代码。它从我们的 PRISM 应用程序的引导程序调用并在 MainThread 上运行。
任务启动时SynchronizationContext.Current 不为空。
var currentScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var ctx = SynchronizationContext.Current;
if (ctx == null)
throw new NullReferenceException();
Task.Factory
.StartNew(
() =>
SearchHelper.CacheSearchResults(_service.GetData())
.ContinueWith(result => UpdateCache(result.Result), currentScheduler);
【问题讨论】:
-
您的代码片段的第一行是否在主 UI 线程上执行?如果是这样,您是否在
Form.Load等处执行此操作,即在Application.Run核心循环内? -
在保存之前,请执行以下操作:
Debug.Assert(SynchronizationContext.Current != null)。它通过了吗? -
如果您使用.net 4.0,您可能会遇到这个问题:stackoverflow.com/q/11621372/495262
-
确实我们正在使用(并且必须)4.0 :-(
-
SynchronizationContext.Current在我们开始时不为空 - 相应地编辑了问题。
标签: c# .net c#-4.0 task-parallel-library