更新时间:2023-01-23 18:07:46
Thread.sleep代码(500)将迫使当前线程等待500毫秒。它的工作原理,但它不是你想要的,如果你的整个应用程序在一个线程中运行。
Thread.Sleep(500) will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.
在这种情况下,你需要使用一个定时器,就像这样:
In that case, you'll want to use a Timer, like so:
using System.Timers;
void Main()
{
Timer t = new Timer();
t.Interval = 500; //In milliseconds here
t.AutoReset = true; //Stops it from repeating
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hello, world!");
}
您还可以设置自动复位为假(或不设置的话),如果你希望计时器重演。
You can also set AutoReset to false (or not set it at all) if you want the timer to repeat itself.