我正在使用以下代码。
public void runThread(){
if (System.Diagnostics.Process.GetProcessesByName("myThread").Length == 0)
{
Thread t = new Thread(new ThreadStart(go));
t.IsBackground = true;
t.Name = "myThread";
t.Start();
}
else
{
System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
}
}
public void go()
{
//My work goes here
}
我多次调用 runThread() 函数,但我希望线程仅在线程未运行时启动。怎么可能?
最佳答案
GetProcessesByName 不会在您的应用程序中查找线程,而是在您的机器中查找进程。事实上,在您自己的应用程序中没有很好的方法来查询线程(一个问题是编写调试器)。
对于你想要的,你可以创建一个 wrapper class for your threads这样您就可以查询它们是否正在运行。或者 keep track of the threads yourself by other means .
您也可以考虑使用 测试后Lazy<Thread>
需要时会初始化的字段,可以查询线程是否存活。Lazy<Thread>
这不是一个好主意。
源自 Simon's answer :
private int running;
public void runThread()
{
if (Interlocked.CompareExchange(ref running, 1, 0) == 0)
{
Thread t = new Thread
(
() =>
{
try
{
go();
}
catch
{
//Without the catch any exceptions will be unhandled
//(Maybe that's what you want, maybe not*)
}
finally
{
//Regardless of exceptions, we need this to happen:
running = 0;
}
}
);
t.IsBackground = true;
t.Name = "myThread";
t.Start();
}
else
{
System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
}
}
public void go()
{
//My work goes here
}
Wajid和 Segey是对的。您可以只拥有一个 Thread 字段。请允许我举个例子:
private Thread _thread;
public void runThread()
{
var thread = _thread;
//Prevent optimization from not using the local variable
Thread.MemoryBarrier();
if
(
thread == null ||
thread.ThreadState == System.Threading.ThreadState.Stopped
)
{
var newThread = new Thread(go);
newThread.IsBackground = true;
newThread.Name = "myThread";
newThread.Start();
//Prevent optimization from setting the field before calling Start
Thread.MemoryBarrier();
_thread = newThread;
}
else
{
System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
}
}
public void go()
{
//My work goes here
}
注意:最好使用第一个备选方案(源自 Simon 的回答),因为它是线程安全的。也就是说,如果有多个线程同时调用 runThread 方法,则不会有创建多个线程的风险。
关于c# - 检测线程已在 C# .net 中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949024/