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

前端 未结 5 553
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 16:50

I know there are other posts that say you can create a control and then check the InvokeRequired property to see if the current thread is the main thread or not

5条回答
  •  星月不相逢
    2020-12-04 17:01

    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...
    }
    

提交回复
热议问题