There are other posts that say you can create a control in windows forms and then check the InvokeRequired
property to see if the current thread is the main thread or not.
The problem is that you have no way of knowing if that control itself was created on the main thread.
I am using the following code to tell if a thread is the main thread (the thread that started the process):
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA || Thread.CurrentThread.ManagedThreadId != 1 || Thread.CurrentThread.IsBackground || Thread.CurrentThread.IsThreadPoolThread) { // not the main thread }
Does anyone know a better way? It seems like this way might be prone to errors or break in future versions of the runtime.
You could do it like this:
// Do this when you start your application static int mainThreadId; // In Main method: mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId; // If called in the non main thread, will return false; public static bool IsMainThread { get { return System.Threading.Thread.CurrentThread.ManagedThreadId == mainThreadId; } }
EDIT I realized you could do it with reflection too, here is a snippet for that:
public static void CheckForMainThread() { if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA && !Thread.CurrentThread.IsBackground && !Thread.CurrentThread.IsThreadPoolThread && Thread.CurrentThread.IsAlive) { MethodInfo correctEntryMethod = Assembly.GetEntryAssembly().EntryPoint; StackTrace trace = new StackTrace(); StackFrame[] frames = trace.GetFrames(); for (int i = frames.Length - 1; i >= 0; i--) { MethodBase method = frames[i].GetMethod(); if (correctEntryMethod == method) { return; } } } // throw exception, the current thread is not the main thread... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With