Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a thread is the main thread in C#

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.

like image 339
jjxtra Avatar asked Mar 03 '10 19:03

jjxtra


1 Answers

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... } 
like image 127
Zach Johnson Avatar answered Sep 19 '22 09:09

Zach Johnson