定时器分两种,一种是阻塞方式,一种是非阻塞
@1.1:阻塞方式的定时器,调用sleep使当前线程休眠,终端无法输入字符
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Out.WriteLine("1->");
Thread.Sleep(2000);
}
}
} class Program
{
[DllImport("kernel32.dll")]
static extern uint GetTickCount();
static void Main(string[] args)
{
while (true)
{
Console.Out.WriteLine("1->");
// Thread.Sleep(2000);
Delayms(2000);
}
}
//延时delayms毫秒
static void Delayms(uint delayms)
{
uint startms = GetTickCount();
while (GetTickCount() - startms < delayms){}
}
}@1.3 在网上看到的另一种轮询代码,当然也不可取
//延时delays秒
static void Delays(uint delays)
{
DateTime chaoshi = DateTime.Now.AddSeconds(delays); //定义超时时间 当前时间上加上 定义的超时的秒
DateTime bidui = DateTime.Now; //声明一个比对的时间 这个是当前时间哦
while (DateTime.Compare(chaoshi, bidui) == 1) //通过比对函数 DateTime.Compare 比对 定义的超时时间 是不是大于 当前时间 。直到大于的时候才退出循环达到延时的目的。
{
bidui = DateTime.Now;
}
}
class Program
{
[DllImport("kernel32.dll")]
static extern uint GetTickCount();
static void Main(string[] args)
{
System.Timers.Timer aTimer = new System.Timers.Timer();
//添加响应函数
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// 间隔设置为2000毫秒
aTimer.Interval = 2000;
aTimer.Enabled = true;
int ni=0;
while (true)
{
Console.Out.WriteLine(ni++);
Thread.Sleep(1000);
}
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("<--------->");
}
}
原文:http://blog.csdn.net/x356982611/article/details/22926883