等待线程变为活动的无限循环{while!thread.isAlive;}

本文关键字:while thread isAlive 无限循环 线程 活动 等待 | 更新日期: 2023-09-27 18:00:03

我正在创建一个应用程序,它需要在新线程中做一些工作,并将结果保存到静态列表中,然后线程自然死亡。一次只能有一个额外线程的实例在执行,所以当负责创建线程的函数发现线程已经在工作时,它应该返回。

创建应用程序时,我在msdn上使用了此指南:http://msdn.microsoft.com/en-us/library/7a2f3ay4%28v=vs.80%29.aspx

本指南中写道:

// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
// Loop until worker thread activates.
while (!workerThread.IsAlive);
// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);

所以我在我的应用程序中使用了这个代码:

if (TibiaControl.PathFinder.PathFinderThread != null && TibiaControl.PathFinder.PathFinderThread.IsAlive)
    return false;
TibiaControl.PathFinder Finder = new TibiaControl.PathFinder(targetX, targetY);
TibiaControl.PathFinder.PathFinderThread = new Thread(new ThreadStart(Finder.FindPath));
TibiaControl.PathFinder.PathFinderThread.Start();
SystemControl.DebugMessage(0, "_findPath -- 1");
while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;
Thread.Sleep(1);
SystemControl.DebugMessage(0, "_findPath -- 2");

但当高频执行这个功能时(比如每20-30ms一次),我的应用程序会卡在上

while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;

行和主线程被困在一个无限循环中(就好像线程在while循环发生之前已经完成了它的工作一样)。我该怎么解决?

等待线程变为活动的无限循环{while!thread.isAlive;}

我认为您可能已经盲目地从示例中复制了一些您不需要的代码:

while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;
Thread.Sleep(1);

他们这样做的原因是为了证明RequestStop方法的有用性。

我不会将该代码用作任何有用应用程序的源代码。首先,线程有更好的等待方式。例如,ManualResetEventSlim。其次,从您发布的代码中很难判断IsAlive是否为volatile。甚至,在一个x86系统中,它真的不做任何关于特殊代码的事情。我建议使用更安全、更明确的线程安全值读取形式。例如:

while (0 == Interlocked.Read(ref workerThread.IsAlive)); 

这意味着更改为创建一个新变量IsAlivelong。但是,在一个单一的CPU系统中,你只是让唯一的CPU繁忙,其他线程几乎没有机会使用它。你应该把控制权交给其他线程:

while (0 == Interlocked.Read(ref workerThread.IsAlive)) Thread.Sleep(1);

但是,我认为从开始示例代码是个坏主意。试着弄清楚你需要做什么,并详细说明。。。

有关更多信息,请参阅http://msdn.microsoft.com/en-us/magazine/jj863136.aspx和http://msdn.microsoft.com/en-us/magazine/jj883956.aspx

将IsAlive循环与查询ThreadState:结合起来

while (!myThread.IsAlive 
    && myThread.ThreadState != ThreadState.Stopped
    && myThread.ThreadState != ThreadState.Aborted)
{}

这避免了线程在启动后立即停止的情况下的无休止循环