我正在使用以下代码。
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()函数,但我希望线程仅在线程未运行时启动。怎么可能?
答案 0 :(得分:6)
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,则不存在创建多个线程的风险。
答案 1 :(得分:2)
一个简单的方法是你可以有一个标志,指示它是否正在运行。如果发生冲突,你可能需要使用一些lock
。
public static bool isThreadRunning = false;
public void runThread()
{
if (!isThreadRunning)
{
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()
{
isThreadRunning = true;
//My work goes here
isThreadRunning = false;
}
答案 2 :(得分:1)
您可以使用Thread.IsAlive
检查prevoius线程是否正在运行。这是为了给出线程状态。您可以在mythread.Start().
之前进行此检查
答案 3 :(得分:0)
您是否仅在运行线程方法中创建线程?如果是这样的话,请将其保存为包含runThread方法的类的字段并询问t.IsAlive。
答案 4 :(得分:0)
也许这可以帮到你
static bool isRunning = false;
public void RunThread(){
if (!isRunning)
{
Thread t = new Thread(()=> { go(); isRunning = true;});
t.IsBackground = true;
t.Name = "myThread";
t.Start();
}
else
{
System.Diagnostics.Debug.WriteLine("myThread is already Running.");
}
}
public void go()
{
//My work goes here
}