• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 23207
  • Last Modified:

c# better sleep

I wrote a program that does something every 10 seconds.  I am using a sleep, but the program seems to lock up duding the sleep.  Is there a better way to do this so the program is not locked up and will respond to a button press?  Basically I start the process wiht one button and it loops 1000 times until another button is pressed and a flag is set to false.  Currently I have to keep pressing the stop button since the program seems to lock.



  • 2
1 Solution
Sleep causes your thread to release the CPU for the requested time, so it would be dead for that period.

You can do what you want by using a System.Timer. Start it up, and it will fire an event each time the ttimer fires. You can do what you need in the event handler.

jackjohnson44Author Commented:
can you please privide some code, I don't really understand.

1. Add this member to your form class:
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

2. In your form class, add this:
// This is the method to run when the timer is raised.
private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
   // Perform the action you want to take each time the timer fires.

2. In the code where you perfom class-levei initialization, add this:
// Add the event and the event handler for the method that will process the timer firing.
myTimer.Tick += new EventHandler(TimerEventProcessor);

3. Whenever you want to start the timer running, execute this:
// Sets the timer interval to 10 seconds. (Interval is in ms)
myTimer.Interval = 10000;

4. When you want the timer to stop, execute this:

You can get more information here:



Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now