[英]How to pause/suspend a thread then continue it?
I am making an application in C# which uses a winform as the GUI and a separate thread which is running in the background automatically changing things.我正在用 C# 制作一个应用程序,它使用一个 winform 作为 GUI 和一个在后台运行的单独线程,自动更改内容。 Ex:
前任:
public void Run()
{
while(true)
{
printMessageOnGui("Hey");
Thread.Sleep(2000);
// Do more work
}
}
How would I make it pause anywhere in the loop, because one iteration of the loop takes around 30 seconds.我如何让它在循环中的任何地方暂停,因为循环的一次迭代需要大约 30 秒。 So I wouldn't want to pause it after its done one loop, I want to pause it on time.
所以我不想在完成一个循环后暂停它,我想按时暂停它。
var 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();
You should do this via a ManualResetEvent .您应该通过ManualResetEvent执行此操作。
ManualResetEvent mre = new ManualResetEvent();
mre.WaitOne(); // This will wait
On another thread, obviously you'll need a reference to the mre在另一个线程上,显然您需要对 mre 的引用
mre.Set(); // Tells the other thread to go again
A full example which will print some text, wait for another thread to do something and then resume:一个完整的例子,它将打印一些文本,等待另一个线程做一些事情然后继续:
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();
}
}
You can pause a thread by calling thread.Suspend
but that is deprecated.您可以通过调用
thread.Suspend
来暂停一个线程,但该方法已被弃用。 I would take a look at autoresetevent for performing your synchronization.我会看看用于执行同步的autoresetevent 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.