Mar*_*age 14
您可以在循环中添加此调用:
System.Threading.Thread.Sleep(5000); // 5,000 ms
Run Code Online (Sandbox Code Playgroud)
或者更好的可读性:
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
Run Code Online (Sandbox Code Playgroud)
但是,如果您的应用程序具有用户界面,则不应该在前台线程(处理应用程序消息循环的线程)上休眠.
ado*_*lot 11
您可以尝试使用Timer,
using System;
public class PortChat
{
public static System.Timers.Timer _timer;
public static void Main()
{
_timer = new System.Timers.Timer();
_timer.Interval = 5000;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
Console.ReadKey();
}
static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//Do Your loop
}
}
Run Code Online (Sandbox Code Playgroud)
此外,如果你的循环操作持续时间超过5秒,你可以设置
_timer.AutoReset = false;
Run Code Online (Sandbox Code Playgroud)
禁用下一个计时器滴答,直到操作完成循环
但是然后结束循环你需要再次启用计时器
_timer.Enabled = true;
Run Code Online (Sandbox Code Playgroud)