我正在創建一個應用程序,需要在新線程中完成一些工作並將結果保存到靜態列表中,然後線程自然死亡。這個附加線程只能有一個實例在執行,所以當負責創建線程查找線程的函數已經工作時,它應該返回。無限循環等待線程變爲活動{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