Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pausing a method for set # of milliseconds

Tags:

I need to do a sort of "timeout" or pause in my method for 10 seconds (10000 milliseconds), but I'm not sure if the following would work as i do not have multi-threading.

Thread.Sleep(10000);

I will try to use that current code, but I would appreciate if someone could explain the best and correct way of doing this, especially if the above code does not work properly. Thanks!

UPDATE: This program is actually a console application that in the function in question is doing many HTTPWebRequests to one server, so I wish to delay them for a specified amount of milliseconds. Thus, no callback is required - all that is needed is an "unconditional pause" - basically just the whole thing stops for 10 seconds and then keeps going. I'm pleased that C# still considers this as a thread, so Thread.Sleep(...) would work. Thanks everybody!

like image 799
Maxim Zaslavsky Avatar asked Jul 01 '09 09:07

Maxim Zaslavsky


People also ask

How do you pause a method in Java?

sleep in Java. Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.

How do you pause a function?

The pause() function is used to pause the execution of the current program and wait for the user to press the enter key to terminate its operation.

How do you pause a method in C#?

To pause a thread in C#, use the sleep() method.


2 Answers

You may not have multi-threading, but you're still executing within a thread: all code executes in a thread.

Calling Thread.Sleep will indeed pause the current thread. Do you really want it to unconditionally pause for 10 seconds, or do you want to be able to be "woken up" by something else happening? If you're only actually using one thread, calling Sleep may well be the best way forward, but it will depend on the situation.

In particular, if you're writing a GUI app you don't want to use Thread.Sleep from the UI thread, as otherwise your whole app will become unresponsive for 10 seconds.

If you could give more information about your application, that would help us to advise you better.

like image 122
Jon Skeet Avatar answered Oct 06 '22 08:10

Jon Skeet


Thread.Sleep is fine, and AFAIK the proper way. Even if you are not Multithreaded: There is always at least one Thread, and if you send that to sleep, it sleeps.

Another (bad) way is a spinlock, something like:

// Do never ever use this
private void DoNothing(){ }

private void KillCPU()
{
    DateTime target = DateTime.Now.AddSeconds(10);
    while(DateTime.Now < target) DoNothing();
    DoStuffAfterWaiting10Seconds();
}

This is sadly still being used by people and while it will halt your program for 10 seconds, it will run at 100% CPU Utilization (Well, on Multi-Core systems it's one core).

like image 44
Michael Stum Avatar answered Oct 06 '22 07:10

Michael Stum