我正在创建一个应用程序,需要在新线程中完成一些工作并将结果保存到静态列表中,然后线程自然死亡。这个附加线程只能有一个实例在执行,所以当负责创建线程查找线程的函数已经工作时,它应该返回。无限循环等待线程变为活动{while!thread.isAlive; }
当创建我的appliaction我使用MSDN上该指南:http://msdn.microsoft.com/en-us/library/7a2f3ay4%28v=vs.80%29.aspx
本指南说:
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");
但当:
// 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);
所以我在我的应用程序中使用此代码高频执行此功能(如每20-30ms一次),它发生我的应用程序卡住
线和主线程卡在无限循环(好像线程已经拥有了它是一个while循环发生之前所做的工作)。我该如何解决这个问题?
编写代码后立即停止的情况。请阅读[faq]和[ask] – 2013-02-19 15:43:36
为什么要让主循环暂停,直到工作线程启动? – mbeckish 2013-02-19 15:49:47
如果您只是要阻止主线程,直到工作线程完成使用工作线程获得的内容为止?为什么不在当前线程中完成这项工作? – Servy 2013-02-19 15:50:32