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!
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).