Get running thread by name from ProcessThreadCollection

我们两清 提交于 2021-02-18 20:58:32

问题


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

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

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?

Thank you in advance


回答1:


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.

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.

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




回答2:


ProcessThread represents an operating system-level thread, while Thread represents a .Net managed thread. An operating system-level thread doesn't have a name but a unique ID (just like a process does).

Instead of checking in the list of current thread if your thread is still running, you probably should change the logic of your code. For example, you could keep a boolean containing the state of your thread and update it when it starts/ends.




回答3:


I don't think there is a way to do that. A ProcessThread represents an OS thread. A Thread represents a managed thread inside your application. There isn't really a relationship between the two. Furthermore, the mapping of Thread and ProcessThread is NOT 1:1, as in, a ProcessThread can represent multiple Threads.



来源:https://stackoverflow.com/questions/24084958/get-running-thread-by-name-from-processthreadcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!