How to execute the loop for specific time

How can i execute the a particluar loop for specified time

Timeinsecond = 600

int time = 0;
while (Timeinsecond > time)
{
   // do something here
}

How can i set the time varaible here, if i can use the Timer object start and stop method it doesnot return me time in seconds

Regards NewDev


Solution 1:

May be the following will help:

  Stopwatch s = new Stopwatch();
  s.Start();
  while (s.Elapsed < TimeSpan.FromSeconds(600)) 
  {
      //
  }

  s.Stop();

Solution 2:

If you want ease of use:

If you don't have strong accuracy requirements (true millisecond level accuracy - such as writing a high frames per second video game, or similar real-time simulation), then you can simply use the System.DateTime structure:

// Could use DateTime.Now, but we don't care about time zones - just elapsed time
// Also, UtcNow has slightly better performance
var startTime = DateTime.UtcNow;

while(DateTime.UtcNow - startTime < TimeSpan.FromMinutes(10))
{
    // Execute your loop here...
}

Change TimeSpan.FromMinutes to be whatever period of time you require, seconds, minutes, etc.

In the case of calling something like a web service, displaying something to the user for a short amount of time, or checking files on disk, I'd use this exclusively.

If you want higher accuracy:

look to the Stopwatch class, and check the Elapsed member. It is slightly harder to use, because you have to start it, and it has some bugs which will cause it to sometimes go negative, but it is useful if you need true millisecond-level accuracy.

To use it:

var stopwatch = new Stopwatch();
stopwatch.Start();

while(stopwatch.Elapsed < TimeSpan.FromSeconds(5))
{
    // Execute your loop here...
}