如何暂停/暂停一个线程然后继续它?

我在C#中创建一个应用程序,它使用winform作为GUI和一个在后台运行的独立线程自动更改东西。 例如:

public void Run() { while(true) { printMessageOnGui("Hey"); Thread.Sleep(2000); // Do more work } } 

如何让它在循环中的任何位置暂停,因为循环的一次迭代大约需要30秒。 所以我不想在完成一个循环之后暂停它,我想按时暂停它。

 ManualResetEvent mrse = new ManualResetEvent(false); public void run() { while(true) { mrse.WaitOne(); printMessageOnGui("Hey"); Thread.Sleep(2000); . . } } public void Resume() { mrse.Set(); } public void Pause() { mrse.Reset(); } 

您应该通过ManualResetEvent执行此操作。

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

在另一个线程上,显然你需要一个对mre的引用

 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(); } } 

您可以通过调用thread.Suspend暂停一个线程但不推荐使用。 我会看看autoresetevent来执行同步。