1

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!

Brian Gideon
  • 47,849
  • 13
  • 107
  • 150
Kracken
  • 662
  • 1
  • 11
  • 27

3 Answers3

7

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();
}
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
3

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
1

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.

Community
  • 1
  • 1
m-sharp
  • 16,443
  • 1
  • 26
  • 26