2013-07-04 27 views
9

如何將線程置於暫停/睡眠狀態,直到我手動恢復它在C#中?暫停一個線程,直到手動恢復

目前我中止線程,但這不是我正在尋找的。線程應該休眠/暫停,直到它觸發它喚醒。

+1

我從來沒有這樣做過,但我一起阻斷的思路思考線程使用ManualResetEvent。 –

+0

@ByteBlast:它看起來像是重複的,但是對另一個問題的回答並不是特別好:/ – Ian

+0

確保只對後臺線程執行此操作。 UI線程(任何已加入COM STA的線程,通常是主線程,並且通常是任何擁有窗口的線程)*必須*繼續運行並泵送消息,否則將導致穩定性問題。 –

回答

18

您應該通過ManualResetEvent來做到這一點。

ManualResetEvent mre = new ManualResetEvent(); 
mre.WaitOne(); // This will wait 

在另一個線程上,顯然你需要一個對ManualResetEvent實例的引用。

mre.Set(); // Tells the other thread to go again 

完整的例子,它將打印一些文本,等待另一個線程做一些事情,然後重新開始:

class Program 
{ 
    private static ManualResetEvent mre = new ManualResetEvent(false); 

    static void Main(string[] args) 
    { 
     Thread t = new Thread(new ThreadStart(SleepAndSet)); 
     t.Start(); 

     Console.WriteLine("Waiting"); 
     mre.WaitOne(); 
     Console.WriteLine("Resuming"); 
    } 

    public static void SleepAndSet() 
    { 
     Thread.Sleep(2000); 
     mre.Set(); 
    } 
} 
+0

謝謝你的幫助。對此,我真的非常感激! –

+0

@騎士:沒問題,請記住接受答案,如果有幫助。 – Ian

+0

是的,抱歉,我忘了:) –