FredVaz
FredVaz

Reputation: 533

How can i put a delay with C#?

I want to make an application to execute several instructions to pass the following instruction has to wait a few milliseconds.

Such that:

while(true){

  send("OK");
  wait(100); //or such delay(100);

}

Is it possible in C#?

Upvotes: 11

Views: 47863

Answers (8)

Notts90
Notts90

Reputation: 255

This would be a much better option as it doesn't lock up the current thead and make it unresponsive.

Create this method

    async System.Threading.Tasks.Task WaitMethod()
    {
        await System.Threading.Tasks.Task.Delay(100);
    }

Then call like this

    public async void MyMethod()
    {
        while(true)
        {
            send("OK");
            await WaitMethod();
        }
    }

Don't forge the async in the method that calls the delay!

For more info see this page I found when trying to do a similar thing

Upvotes: 4

Abdul
Abdul

Reputation: 854

Thread.Sleep() is the solution.It can be used to wait one thread untill other thread completes it's working OR After execution of one instruction someone wants to wait time before executing the later statement. It has two overloaded method.first take int type milisecond parameter while second take timespan parameter. 1 Milisecond=1/1000s OR 1 second=1000 Miliseconds Suppose if someone wants to wait for 10 seconds code will be....

System.Threading.Thread.Sleep(10000);

for more details about Thread.Sleep() please visit http://msdn.microsoft.com/en-us/library/274eh01d(v=vs.110).aspx

Happy Coding.....!

Upvotes: 1

iefpw
iefpw

Reputation: 7042

Thread.Sleep(milliseconds) should stop the application for that second. Read up on Thread.Sleep in MSDN.

Upvotes: 5

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31641

To sleep for 100ms use Thread.Sleep

While(true){    
  send("OK");
  Thread.Sleep(100);
}

Upvotes: 6

Grant Thomas
Grant Thomas

Reputation: 45083

You can use Thread.Sleep, but I'd highly discourage it, unless you A) know for a fact it is appropriate and B) there are no better options. If you could be more specific in what you want to achieve, there will likely be better alternatives, such as using events and handlers.

Upvotes: 5

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

Yes, you can use the Thread.Sleep method:

while(true)
{
  send("OK");
  Thread.Sleep(100); //Sleep for 100 milliseconds
}

However, sleeping is generally indicative of a suboptimal design decision. If it can be avoided I'd recommend doing so (using a callback, subscriber pattern etc).

Upvotes: 4

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You can use the Thread.Sleep() method to suspend the current thread for X milliseconds:

// Sleep for five seconds
System.Threading.Thread.Sleep(5000);

Upvotes: 12

Neil Knight
Neil Knight

Reputation: 48537

Thread.Sleep(100); will do the trick. This can be found in the System.Threading namespace.

Upvotes: 24

Related Questions