views:

179

answers:

2

Here is the problem I have: I need to make sure an object is instantiated on the UI thread. If it is not, it should throw an exception. But how do I check inside a method whether it is running on the UI thread? Note: I do not want to pass any information into the object's constructor.

The perfect candidate would be the DispatcherSynchronizationContext (WPF implementation of SynchronizationContext) which internally holds a reference to Dispatcher which references the thread it's associated with, but unfortunately that field is private so there is no way for me to access it.

+5  A: 

Small clarification, although there is typically only 1 UI thread there can be many UI threads. This is true for both WPF and WinForms.

The best way I've found to achieve this though is with a SynchronizationContext. Both WPF and WinForms will establish a SynchronizationContext on any thread they are running UI on. This is the function I use if I am not tied to any particular UI model.

public bool IsPossiblyUIThread() {
  return SynchronizationContext.Current != null;
}

Note, it is not in any way foolproof. It's possible for non-UI components to establish a SynchronizationContext and this would return true for a simple worker thread. Hence the non-authoritative name.

A slightly more reliable way to do this is as follows. But it requires you to reference at least a portion of WPF to implement.

public bool IsLikelyWpfUIThread() {
  var context = SynchronizationContext.Current;
  return context != null && context is DispatcherSynchronizationContext;
}
JaredPar
Yes, this seems to be the best way. Thanks so much!
Hermann
A: 

Dispatcher.CheckAccess() returns true if your code runs on the same Thread as the Dispatcher. It should work if there is only one Dispatcher/UIThread.

iik
This might be true, but note that the Dispatcher is always associated with the thread it was created on. So using Dispatcher.CheckAccess() does not help you much if the object was created on a another thread.
Hermann