如何判断一个线程是用C#主线程 [英] How to tell if a thread is the main thread in C#

查看:282
本文介绍了如何判断一个线程是用C#主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一些说,你可以创建一个控件,然后检查 InvokeRequired 属性,查看是否当前线程是主线程或没有其他职位。

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.

现在的问题是,你有没有办法,如果该控件本身是在主线程创建得知。

The problem is that you have no way of knowing if that control itself was created on the main thread.

我使用下面的code说,如果一个线程是主线程(即启动该进程的线程):

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

这篇关于如何判断一个线程是用C#主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆