【发布时间】:2014-07-27 21:48:14
【问题描述】:
在搜索 Stack Overflow 问题和谷歌搜索后,我仍然没有得到它。
我知道您可以使用“Thread.isAlive()”方法检查单个线程是否正在运行,但我想检查当前进程的所有正在运行的线程之间是否仍在运行特定的“FooThread”,并且如果没有,请调用启动它的方法。
//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 关闭时,请不要。当它开始时,记下。
-
你做的事情非常非常错误。任何“是一个仍在运行测试的线程”都是无用的,它可能不会在一纳秒后运行。好在它不起作用。
-
这些都是很棒的 cmets,但也值得指出的是,OP 实际上正在检查线程是否没有运行。
-
是的,我同意@Slider345。我只想检查线程是否没有运行,所以我可以启动它。由于线程在启动时被标志触发(例如,当我读取配置文件并且线程的标志先前设置为 true 时),我只想要一种在运行时启动它而无需重新启动程序的方法。
标签: c# .net multithreading process