问题
How can I add a delay to a program in C#?
回答1:
You could use Thread.Sleep()
function, e.g.
int milliseconds = 2000;
Thread.Sleep(milliseconds);
that stops the execution of the current thread for 2 seconds.
Anyway, that could not fit your needs... what exactly are you trying to accomplish ?
回答2:
Use a timer with an interval set to 2–3 seconds.
You have three different options to choose from, depending on which type of application you're writing:
- System.Timers.Timer
- System.Windows.Forms.Timer
- System.Threading.Timer
Don't use Thread.Sleep, as that will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just pausing as you probably intended.
回答3:
For 2.3 seconds you should do:
System.Threading.Thread.Sleep(2300);
回答4:
System.Threading.Thread.Sleep(
(int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);
Or with using
statements:
Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
I prefer this to 1000 * numSeconds
(or simply 3000
) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep
before. It better documents your intent.
来源:https://stackoverflow.com/questions/5449956/how-to-add-a-delay-for-a-2-or-3-seconds