Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check If Thread Is on Gui Context

Tags:

c#

wpf

How can I check if the current running thread is on the GUI context or not?

like image 964
Robert Avatar asked Dec 01 '10 01:12

Robert


2 Answers

It's unfortunately hard to answer this question with 100% accuracy because it's not always entirely obvious what constitutes a GUI Context. It's more of a heuristic than a yes / no answer. And the heuristic will be different for every GUI framework.

For WPF a good one is to check and see if there as an active Dispatcher for the current thread

public static bool IsWpfGuiThread() {
  return Dispatcher.FromThread(Thread.CurrentThread) != null;
}

However this can be fooled by just setting up a Dispatcher on a random thread but not actually putting a GUI on top of it.

For WinForms a good one to check is the current SynchronizationContext.

public static bool IsWinFormsGuiThread() {
  return SynchronizationContext.Current is WindowsFormsSynchronizationContext;
}

However this can be fooled by someone temporarily (or longer) resetting the Current value to another synchronization context. This is essentially just a global thread and can be set by anyone. It's actually fairly common for it to change in certain applications like Visual Studio (but that's a WPF app though)

like image 110
JaredPar Avatar answered Oct 19 '22 14:10

JaredPar


Are you asking if you have a known gui object can you query it to see if you are in the proper context of that object? I think guiObject.VerifyAccess() will work for this.

like image 30
cClark Avatar answered Oct 19 '22 13:10

cClark