Check If Thread Is on Gui Context
How can I check if the current running thread is on the GUI context or not开发者_JS百科?
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)
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.
I think you want the Dispatcher
object. See http://social.msdn.microsoft.com/forums/en-US/wpf/thread/360540eb-d756-4434-86f9-a3449f05eb55
精彩评论