Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sleep function...zzzz....zzzz...

Status
Not open for further replies.

stuartd

Programmer
Jan 8, 2001
146
US
Hi,

I have written the following ugly function. This appears to hog all processor power, so there must be a better way to sleep in a program for a period of time.

Does anyone have any suggestions?

Code:
// Will sleep the program for given number of seconds
private void Sleep(int i_SleepSeconds)
{
   // Locals
   DateTime then;

   then=DateTime.Now;

   while(0==0)
   {
      TimeSpan ts=DateTime.Now - then;

      if(ts.Seconds>i_SleepSeconds)
      {
         break;   // out of while
      }

      // Process events
      Application.DoEvents();
   }
}

Nice.

SD
 
Theres several "correct" ways to sleep an application. Off the top of my head the only way I can think of (and probably not the best way) is to use a Timer control.

In your function you start the time, and set its interval to however long you want.

When the timer reaches its interval, it fires the YourTimer.Tick Event, from there you can continue on with what ever is next.

But digging deeper, why do you want to sleep? If you are waiting for something, the correct way to that is handle the event of that task's completion.
 
I need to copy files from one place to another, and will do it every 60 seconds. As this is external, i can not get an event.

So to use the timer, my copy code would need to be called from the timer event function?

SD
 
system.Threading.Thread.Sleep();

but yes a timmer would be better and you would handle the tixck event

Event better would be to use the system.threading.timer but those are a bit tricky to implement.

Christiaan Baes
Belgium

"Time for a new sig." - Me
 
NeilTrain - timer works great.

It's easy when you know how!

SD
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top