获取正在运行的线程由ProcessThreadCollection名线程、正在运行、ProcessThreadCollection

2023-09-04 13:04:43 作者:细雨斜阳愁

在搜索上的堆栈溢出的问题和一些google搜索后,我仍然没有得到它。

After searching on Stack Overflow questions and some googling, I still not getting it.

我知道,你可以检查,如果一个线程与Thread.isAlive()方法运行,但我想检查是否有特定的FooThread仍与当前进程中的所有正在运行的线程之间的运行,及如果不是,请致电启动它的方法。

I'm aware that you can check if a single thread is running with "Thread.isAlive()" method, but I want to check if a particular "FooThread" is still running between all running threads from current process, and if not, call the method that starts it.

//somewhere in the code, on another Project/DLL inside solution
private void FooThreadCaller()
{
    Action act = () => fooFunction();
    Thread t = new Thread(new ThreadStart(act));
    t.Name = "FooThread";
    t.Start();
}
//...
Process proc = System.Diagnostics.Process.GetCurrentProcess();
ProcessThreadCollection threads = proc.Threads;
bool ThreadExists = false
foreach (ProcessThread item in threads)
{
    // if item.Name == "FooThread", then ThreadExists = true...
    // so, if !ThreadExists then call FooThreadCaller() and so on.
}
//...

由于ProcessThread类没有一个名称属性(如System.Threading.Thread一样),但只有ID,而我只知道线程名(FooThread)没有身份证,我怎么会检查是否FooThread运行/活着?

Since the ProcessThread class doesn't have a "Name" property (like System.Threading.Thread does) but only ID, and I only know the thread name ("FooThread") not the ID, how could I check if "FooThread" is running/alive?

感谢你在前进

推荐答案

正如在其他的答案中,ProcessThread和线程对象不同。您的DLL正在创造它自己的Thread对象,但随后扔掉它引用的对象。再后来就您所查询的OS(通过System.Diagnostics程序),该线程并期待获得同样的水平,你收到的线程的创建者。

As mentioned in the other answers, the ProcessThread and the Thread objects are different. Your dll is creating it's own Thread object, but then it throws away it's reference to that object. Then later on your are querying the OS (through System.Diagnostics) for that thread and expecting the same level of access you had before as the thread's creator.

相反,您应该引用保存到您的Thread对象为您创建它们。也许你的DLL可以实现一个公共静态集合对象,你会再加入您的线程对象的创建他们。

Instead, you should save the references to your Thread objects as you create them. Maybe your dll could implement a public static collection object which you would then add your thread objects to as you create them.

那么你的DLL外,你可以通过收集循环,并检查每个线程的名称和状态。

Then outside of your dll you could loop through the collection and check the names and status of each Thread.