在Stack Overflow问题和一些Google搜索问题上搜索后,我仍然没有得到它。我知道你可以使用“Thread.isAlive()”方法检查单个线程是否正在运行,但是我想检查一个特定的“FooThread”是否仍然在当前进程的所有正在运行的线程之间运行,如果没有,请调用启动它的方法。从ProcessThreadCollection获取正在运行的线程名称
//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 “)不是ID,我如何检查”FooThread“是否正在运行/活着?
预先感谢您
即使这是可能的,它不会是一个好主意。如果线程刚刚退出,您会认为它仍在运行。这本质上是活泼的。跟踪这些信息。当FooThread关闭时,不要。当它开始时,请注意。 – usr
你正在做一些非常非常错误的事情。任何“一个仍在运行测试的线程”都是没用的,它可能不会在纳秒后运行。好东西它不起作用。 –
这些评论很棒,但值得指出的是OP实际上检查线程是否*运行。 – Slider345