Quick while stopping
i have this code:
private STOP = false;
public void Start()
{
while(!STOP)
{
开发者_如何学JAVA //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!
Something along the lines of:
private System.Threading.ManualResetEvent STOP = new System.Threading.ManualResetEvent(false);
public void Start()
{
while(true)
{
//do some work
if(STOP.WaitOne(15000))
break;
}
}
public void Stop()
{
STOP.Set();
}
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:
System.Threading.Timer MyTimer;
public void Start()
{
MyTimer = new Timer((s) =>
{
DoSomeWork();
}, null, 15000, 15000);
}
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.
public void Stop()
{
MyTimer.Dispose();
}
This will be more efficient than using a separate thread that spends most of its time sleeping, but still consuming system resources.
Use ManualResetEvent.WaitOne with timeout.
manualResetEvent.WaitOne(timeout)
Set the event to wake it up, or it will wake up when timed out.
See this related question.
精彩评论