How do I know if I am running on the UI thread in WPF?

The golden rule of WPF multi-threading is “Thou shalt only update UI using code that runs on the same thread as the UI.” If you happen to be running on another thread you use the Dispatcher property of any of your UI elements to get back on to the UI thread. This raises the question - how do I know when I’m on the UI thread? It turns out the Dispatcher has two methods you can use - CheckAccess and VerifyAccess. CheckAccess returns true if you are on the UI thread. VerifyAccess is a more aggressive version of this method and throws an exception if you are not running on the UI thread. Strangely CheckAccess is marked with attributes to prevent it appearing in intellisense in Visual Studio. This CheckAccess method is the WPF equivalent of the InvokeRequired property of the Control object in Windows Forms, which had similar thread-affinity rules to WPF.

On a related note the Arbel Network  Blog has an excellent tip that uses reflection inside of a method to call back in to itself (but on the UI thread) if necessary. They also have a link to Nick Kramer’s threading white paper.