调度程序和工作线程
我有一个关于调度程序和后台工作线程的问题。我有一个异步处理 HTTP 请求的系统。最终,ObservableCollection 绑定到 WPF 控件。
我一直在使用 Dispatcher.CurrentDispatcher.CheckAccess() 代替 Silverlight 的 Deployment.Current.Dispatcher.CheckAccess() 来确定我是否在 UI 线程中。然而,查看 Stack Overflow 上的文档和其他问题,似乎 WPF 版本只是在需要时创建一个调度程序。
当前系统在调度线程上使用 CheckAccess 来确定我们是否在 UI 线程上,然后将其传递给在工作线程中运行的处理程序。工作线程上的 CheckAccess 也返回 true,大概是因为它刚刚创建了自己的 Dispatcher。
迁移到跨线程可观察集合不是一个选择。另一个问题说我需要维护对 UI 线程调度程序的引用。有没有办法使用 Threading 命名空间中的 Dispatcher 类/其他类来确定我是否在 UI 线程中?或者我应该继续使用调度线程的调度程序来运行处理程序,无论调度线程是否是 UI 线程?
谢谢!
I have a question about Dispatchers and background worker threads. I have a system wherein I am asynchronously processing HTTP requests. Eventually, an ObservableCollection gets bound to a WPF control.
I've been using Dispatcher.CurrentDispatcher.CheckAccess() in lieu of Silverlight's Deployment.Current.Dispatcher.CheckAccess() to determine whether I am in the UI thread or not. However, looking at the documentation and other questions here on Stack Overflow, it seems like the WPF version just creates a dispatcher if required.
The current system uses CheckAccess on the scheduling thread to determine whether we are on the UI thread or not and then passes that to a handler that is run in the worker thread. CheckAccess on the worker thread also returns true, presumably because it just created its own Dispatcher.
Moving to a cross-thread observable collection is not an option. Another question said I need to maintain a reference to the UI thread's dispatcher. Is there any way to use the Dispatcher class/other classes in the Threading namespace to determine if I am in the UI thread? Or should I go ahead and use the dispatcher of the scheduling thread to run the handler regardless of whether the scheduling thread was the UI thread or not?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将简单地获取与调用(当前)线程关联的 Dispatcher,如果不存在,则会创建它。正如您所发现的,在该调度程序上调用 CheckAccess() 将返回 true。
您可以尝试使用
Application.Current.Dispatcher
,我的观察表明这是与主 UI 线程关联的调度程序,尽管我不能确定这是否总是 案例。您还需要记住,如果您有多个 UI 线程,这可能不起作用,您将不知道哪个线程拥有绑定到 ObservableCollection 的 UI 元素。在这种情况下,您将需要开始传递对适当调度程序的引用(或 SynchronizationContext)。This will simply get the Dispatcher associated with the calling (current) thread, and if one doesn't exist it will be created. So as you've found, calling CheckAccess() on that dispatcher will return true.
You can try using
Application.Current.Dispatcher
, my observations show that this is the dispatcher associated with the main UI thread, although i can't say for sure if this is always the case. You also need to bear in mind that this may not work if you have more than one UI thread, you won't know which thread owns the UI element that is bound to your ObservableCollection. In this case you will need to start passing round a reference to the appropriate Dispatcher (or SynchronizationContext).