我正在创建一个应用程序,需要在新线程中做一些工作并将结果保存到静态列表,然后线程自然死亡。一次只能执行这个附加线程的一个实例,因此当负责创建线程的函数发现线程已经工作时,它应该返回。
创建我的应用程序时,我在 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-30 毫秒一次),我的应用程序会卡住
while (!TibiaControl.PathFinder.PathFinderThread.IsAlive) ;
行和主线程陷入无限循环(好像线程在while循环发生之前已经完成了它的工作)。我该如何解决?