如何暂停/挂起一个线程然后继续它?
我正在用 C# 制作一个应用程序,它使用 winform 作为 GUI 和一个在后台运行的单独线程,自动更改内容。例如:
public void Run()
{
while(true)
{
printMessageOnGui("Hey");
Thread.Sleep(2000);
// Do more work
}
}
我如何让它在循环中的任何位置暂停,因为循环的一次迭代大约需要 30 秒。所以我不想在完成一个循环后暂停它,我想按时暂停它。
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. 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. So I wouldn't want to pause it after its done one loop, I want to pause it on time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该通过 ManualResetEvent 来执行此操作。
在另一个线程上,显然您需要引用 mre
A 完整示例,它将打印一些文本,等待另一个线程执行某些操作,然后恢复:
You should do this via a ManualResetEvent.
On another thread, obviously you'll need a reference to the mre
A full example which will print some text, wait for another thread to do something and then resume:
您可以通过调用 thread.Suspend 来暂停线程,但这已被弃用。我会看看 autoresetevent 来执行您的操作同步。
You can pause a thread by calling
thread.Suspend
but that is deprecated. I would take a look at autoresetevent for performing your synchronization.