How can I put a delay with C #?

I want to make an application to execute a few instructions to pass the next instruction in order to wait a few milliseconds.

Thus:

while(true){ send("OK"); wait(100); //or such delay(100); } 

Is this possible in C #?

+4
source share
8 answers

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

+17
source

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

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

To sleep for 100 ms, use Thread.Sleep

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

Thread.Sleep (milliseconds) should stop the application for this second. Read Thread.Sleep on MSDN.

+5
source

You can use Thread.Sleep , but I would really discourage it if you do not know that this is indeed the case, and B) there is no better option. If you can be more specific about what you want to achieve, there are likely to be better alternatives, such as using events and handlers.

+5
source

Yes, you can use the Thread.Sleep method :

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

However, a dream usually indicates a suboptimal design decision. If this can be avoided, I would recommend doing it (using a callback, subscriber template, etc.).

+4
source

This will be a much better option, as it does not block the current thead and makes it immune.

Create this method

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

Then call it

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

Do not compress the asynchronous method causing the delay!

For more information, see this page, which I discovered while trying to do a similar thing

+2
source

Thread.Sleep() is the solution. It can be used to wait for one thread until another thread completes its work. OR . After executing one command, someone wants to wait until the later statement is executed. It has two overloaded methods. First you need to enter a parameter of type milisecond of type int, and the second is to use the parameter timepan. 1 Milisecond=1/1000s OR 1 second=1000 Miliseconds Suppose if someone wants to wait 10 seconds, the code will be ....

 System.Threading.Thread.Sleep(10000); 

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

Happy coding .....!

0
source

Source: https://habr.com/ru/post/1395611/


All Articles