C#:当某些事件发生时如何暂停线程并继续?
当某些事件发生时,如何暂停线程并继续?
我希望单击按钮时线程继续。 有人告诉我 thread.suspend 不是暂停线程的正确方法。 还有其他解决方案吗?
How can I pause a thread and continue when some event occur?
I want the thread to continue when a button is clicked.
Someone told me that thread.suspend
is not the proper way to pause a thread.
Is there another solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 System.Threading.EventWaitHandle。
EventWaitHandle 会阻塞,直到收到信号为止。在您的情况下,它将由按钮单击事件发出信号。
您可以像这样发出等待句柄信号:
You could use a System.Threading.EventWaitHandle.
An EventWaitHandle blocks until it is signaled. In your case it will be signaled by the button click event.
You can signal your wait handle like this:
事实上,挂起线程是一种不好的做法,因为您很少确切知道线程当时正在做什么。让线程运行经过
ManualResetEvent 更容易预测
,每次调用WaitOne()
。这将充当门 - 控制线程可以调用Reset()
来关闭门(暂停线程,但安全),并调用Set()
打开门(恢复线程)。例如,您可以在每次循环迭代开始时调用
WaitOne
(如果循环太紧,则每n
迭代调用一次)。Indeed, suspending a thread is bad practice since you very rarely know exactly what a thread is doing at the time. It is more predictable to have the thread run past a
ManualResetEvent
, callingWaitOne()
each time. This will act as a gate - the controlling thread can callReset()
to shut the gate (pausing the thread, but safely), andSet()
to open the gate (resuming the thread).For example, you could call
WaitOne
at the start of each loop iteration (or once everyn
iterations if the loop is too tight).你也可以尝试这个
You can try this also