C# – How to find out whether method executes on UI thread or not in a decoupled way

.netc++ui-threadwpf

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.

Best Solution

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;
}