2

I am trying to add a 1 second delay inside a loop.

What I have done is:

public void Delay()
{
    DateTime end = DateTime.Now.AddSeconds(1);

    while (DateTime.Now <= end)
    {
        //code here
    }
}

and I add the Delay() in my loop.

Is this the best/acceptable way of doing this or can someone recommend a better way?

3
  • 1
    If you can afford to stop the whole thread, you can just use Thread.Sleep(1000). It stops the execution of the thread for 1000ms. Aug 28, 2017 at 7:00
  • 1
    Keep in mind that doing Thread.Sleep(1000) like you have been suggested to will block the current running thread. In case this is not a problem (if this is the only thread), no reason not to do it.
    – Veverke
    Aug 28, 2017 at 7:03
  • @Veverke I would say it is not an issue if the thread is not doing anything else. Aug 28, 2017 at 7:07

3 Answers 3

9
Thread.Sleep (1000);

This 1000 is time duration in milliseconds.

3

Try Thread.Sleep();

using System.Threading;
Thread.Sleep(1000); // 1000 milliseconds i.e 1sec
0

Here a way to do it:

public void Delay(int seconds)
{
    //DateTime end = DateTime.Now.AddSeconds(1);
    //while (DateTime.Now <= end)
    //{
    //}
    System.Threading.Thread.Sleep(seconds * 1000);
}
4
  • 2
    Piero, if you want to abstract the milliseconds and deal only with seconds, there is no need to take care of the conversion, the Sleep has an overload that accepts a TimeSpan. The same would be accomplished directly with Thread.Sleep(TimeSpan.FromSeconds(1));.
    – Veverke
    Aug 28, 2017 at 7:06
  • I didn't know it Aug 28, 2017 at 8:06
  • 1
    thanks. its working now. Aug 28, 2017 at 8:32
  • @AseemMalhotra Good! So, sign it as solution ;) Aug 28, 2017 at 8:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.