How to add a delay for a 2 or 3 seconds [closed]

一曲冷凌霜 提交于 2019-12-17 07:14:12

问题


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:

  1. System.Timers.Timer
  2. System.Windows.Forms.Timer
  3. 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

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