停车时要快
我有这个代码:
private STOP = false;
public void Start()
{
while(!STOP)
{
//do some work
Thread.Sleep(15000);
}
}
public void Stop()
{
STOP = true;
}
但是使用这个代码有时需要等待15秒,如何快速停止这个循环或者可能需要使用其他代码?
谢谢!
i have this code:
private STOP = false;
public void Start()
{
while(!STOP)
{
//do some work
Thread.Sleep(15000);
}
}
public void Stop()
{
STOP = true;
}
But using this code sometimes need to wait a 15 secs, how to quickly stop this cycle or maybe need to use other code?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大致如下:
Something along the lines of:
每当您发现自己编写了一个执行某些操作的循环,然后等待相对较长的时间(甚至一秒很长一段时间!)才能再次执行该操作时,您应该消除该循环并使用计时器。例如,上面的代码可以重写:
计时器将每 15 秒触发一次来完成工作。当需要关闭程序时,只需处理掉计时器即可。
这比使用大部分时间处于睡眠状态但仍然消耗系统资源的单独线程更有效。
Whenever you find yourself writing a loop that does something, then waits a relatively long period of time (even one second is a long time!) to do it again, you should eliminate the loop and use a timer. For example, your code above can be re-written:
The timer will be triggered every 15 seconds to do the work. When it's time to shut down the program, just dispose of the timer.
This will be more efficient than using a separate thread that spends most of its time sleeping, but still consuming system resources.
使用具有超时功能的 ManualResetEvent.WaitOne。
设置事件来唤醒它,否则超时就会唤醒。
请参阅此相关问题。
Use ManualResetEvent.WaitOne with timeout.
Set the event to wake it up, or it will wake up when timed out.
See this related question.