How can i put a delay with C#?

允我心安 提交于 2020-07-18 14:25:27

问题


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#?


回答1:


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




回答2:


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

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



回答3:


To sleep for 100ms use Thread.Sleep

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



回答4:


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.




回答5:


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




回答6:


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).




回答7:


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




回答8:


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.....!



来源:https://stackoverflow.com/questions/9212966/how-can-i-put-a-delay-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!