简体   繁体   English

在C#中引用主线程

[英]Reference to main thread in C#

How do I get a reference to the main thread from another thread in C# ? 如何从C#中的另一个线程获取对主线程的引用?

Why this is needed ? 为什么需要这个? Take for example an assembly loaded to a console application. 例如,加载到控制台应用程序的程序集。 This assembly raises another thread that wants to wait (join) on the main thread of the console application. 这个程序集引发了另一个想要在控制台应用程序的主线程上等待(加入)的线程。 How will it do that ? 它会怎么做?

I thought of this way: In visual studio 2010 you can inspect threads information while debugging. 我这样想:在Visual Studio 2010中,您可以在调试时检查线程信息。 One of the columns in the threads window is the category that specifies if the thread is a worker thread or main thread. 线程窗口中的一列是指定线程是工作线程还是主线程的类别。 Is it possible to get this information ? 是否有可能获得此信息?

Or this way: What about getting the name of the function which is the entry point (main thread ?) and than iterate all threads in current process. 或者这样:获取作为入口点(主线程?)的函数的名称,然后迭代当前进程中的所有线程。 How can I obtain this information ? 我如何获得这些信息?

Thanks. 谢谢。

您可以在创建另一个线程时存储对Thread.CurrentThread (这将是主线程)的引用。

No thread is actually main. 没有线程实际上是主要的。 After you spawn more threads it stops being important which one is main. 在您生成更多线程后,它将停止重要哪一个是主要的。 The only way to find out which thread was created first is to save reference to it in some global static field. 找出首先创建的线程的唯一方法是在某个全局静态字段中保存对它的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM