• 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.

System.Threading.Thread.Sleep(5000);

Thanks

0
jackjohnson44
Asked:
jackjohnson44
  • 2
1 Solution
 
JimBrandleyCommented:
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.

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

Thanks
0
 
JimBrandleyCommented:
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;
myTimer.Start();

4. When you want the timer to stop, execute this:
myTimer.Stop();

You can get more information here:
http://msdn2.microsoft.com/en-us/library/system.windows.forms.timer.aspx

Jim


0

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