2011-09-10 60 views
5

有沒有辦法乾淨地終止從另一個線程調用System.Windows.Forms.Application.Run()發出的消息循環?C# - 終止Application.Run()

Thread messageLoop = new Thread(() => Application.Run()); 
messageLoop.SetApartmentState(ApartmentState.STA); 
messageLoop.Start(); 
//How to terminate thread like on Application.ExitThread() without calling Thread.Abort()? 

在此先感謝!

回答

11

使用ApplicationContext類來保持對線程的引用。像這樣:

ApplicationContext threadContext; 

    private void startLoop() { 
     threadContext = new ApplicationContext(); 
     var messageLoop = new Thread(() => Application.Run(threadContext)); 
     messageLoop.Start(); 
    } 

    private void stopLoop() { 
     threadContext.ExitThread(); 
     threadContext = null; 
    } 
+1

擊敗亞1秒! ;-) –

+1

呵呵,測試示例代碼耗時超過一秒鐘。 –

+1

哼,測試schmesting! –