当前位置: 编程技术>.net/c#/asp.net
C# Timer类的简单例子
来源: 互联网 发布时间:2014-08-30
本文导语: 本节内容: C# Timer类 C# 有三种不同的Timer类: 1,Threading.Timer 2,Timer.Timer 3,Forms.Timer 例子: 代码示例: //c# Timer类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; nam...
本节内容:
C# Timer类
C# 有三种不同的Timer类:
1,Threading.Timer
2,Timer.Timer
3,Forms.Timer
例子:
代码示例:
//c# Timer类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TimerTest
{
class Program
{
public static Timer timer1 = new Timer(new TimerCallback(timer1Callback), null, 50, 50);
public Timer timer2 = new Timer(new TimerCallback(timer2Callback), null, 50, 50);
static void Main(string[] args)
{
Thread.CurrentThread.Name = "MainThread";
Program p = new Program();
Program.timer1.Change(0,50);
p.timer2.Change(0, 50);
p.timer2.Change(0, Timeout.Infinite);
Console.ReadKey();
} // www.
public static void timer2Callback(object o)
{
Thread.CurrentThread.Name = "Timer2";
Console.WriteLine(Thread.CurrentThread.Name + " is running ! Time: " + DateTime.Now + "timer2Callback called!");
}
public static void timer1Callback(object o)
{
Thread.CurrentThread.Name = "Timer1";
Console.WriteLine(Thread.CurrentThread.Name+ " is running ! Time: "+ DateTime.Now +"timer1Callback called!");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TimerTest
{
class Program
{
public static Timer timer1 = new Timer(new TimerCallback(timer1Callback), null, 50, 50);
public Timer timer2 = new Timer(new TimerCallback(timer2Callback), null, 50, 50);
static void Main(string[] args)
{
Thread.CurrentThread.Name = "MainThread";
Program p = new Program();
Program.timer1.Change(0,50);
p.timer2.Change(0, 50);
p.timer2.Change(0, Timeout.Infinite);
Console.ReadKey();
} // www.
public static void timer2Callback(object o)
{
Thread.CurrentThread.Name = "Timer2";
Console.WriteLine(Thread.CurrentThread.Name + " is running ! Time: " + DateTime.Now + "timer2Callback called!");
}
public static void timer1Callback(object o)
{
Thread.CurrentThread.Name = "Timer1";
Console.WriteLine(Thread.CurrentThread.Name+ " is running ! Time: "+ DateTime.Now +"timer1Callback called!");
}
}
}
说明:
1,不保证每个timer对应的线程间的同步。
每隔一断区间打开一个线程来执行timercallback里的操作。
2,就算把时间区间写成1也还是要等到55毫秒才会执行下一个timer。