Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C#
Tip/Trick

Alternate to Thread.Sleep

Rate me:
Please Sign up or sign in to vote.
1.02/5 (31 votes)
27 Apr 2011CPOL 28.2K   4   14
I coded this small stub to waste time as an alternate to Thread.Sleep:
private void WasteTime(TimeSpan unit)
{
  DateTime now = DateTime.Now;
  DateTime then = DateTime.Now + unit;

  while (now < then)
  {
    now = DateTime.Now;
  }
}


Works quite preceisely.

private void WasteTime(TimeSpan unit)
{
  DateTime then = DateTime.Now + unit;
  while (DateTime.Now < then)
  {;}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 1 Wastes CPU cycles Pin
Finger529-Jul-11 8:26
Finger529-Jul-11 8:26 
GeneralTime has passed (i was waiting :-)) now I found the word for... Pin
johannesnestler2-May-11 2:15
johannesnestler2-May-11 2:15 
Time has passed (i was waiting Smile | :) ) now I found the word for this anti-pattern: http://en.wikipedia.org/wiki/Busy_spin
GeneralThe only time I needed something like this code was when I h... Pin
Nougat H.28-Apr-11 2:24
Nougat H.28-Apr-11 2:24 
GeneralPointless Pin
Nagy Vilmos28-Apr-11 0:48
professionalNagy Vilmos28-Apr-11 0:48 
GeneralThere is difference between : DateTime waitForDating = DateT... Pin
Rajin Sayeed S Alam27-Apr-11 22:02
Rajin Sayeed S Alam27-Apr-11 22:02 
GeneralThis is a fantastic example... of what to never do! Pin
AspDotNetDev27-Apr-11 10:49
protectorAspDotNetDev27-Apr-11 10:49 
GeneralThis blocks, so why call it? Pin
Greg Osborne27-Apr-11 7:10
Greg Osborne27-Apr-11 7:10 
GeneralTry Thread.SpinWait(1000000000) for a change. Pin
Kerem Kat27-Apr-11 5:36
Kerem Kat27-Apr-11 5:36 
GeneralYes, I'd call it WastTimeAndCPUAndPower :-) Pin
johannesnestler21-Apr-11 3:44
johannesnestler21-Apr-11 3:44 
GeneralRe: Of course. I agreed with above two comments. Whatever the im... Pin
CodingLover27-Apr-11 23:23
CodingLover27-Apr-11 23:23 
GeneralBut you do realize that they are not the same right? Because... Pin
Karthik. A20-Apr-11 16:34
Karthik. A20-Apr-11 16:34 
GeneralPointless and Inefficeint Pin
Nagy Vilmos28-Apr-11 0:45
professionalNagy Vilmos28-Apr-11 0:45 
GeneralWhy? Pin
Andrew Rissing20-Apr-11 3:58
Andrew Rissing20-Apr-11 3:58 
GeneralCPU hog Pin
Indivara20-Apr-11 2:29
professionalIndivara20-Apr-11 2:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.