这个Timer比较原始
Timer t = new Timer(delegate(object o) {Console.WriteLine("...");}, null, 10000, 1000);
4个参数
1. TimerCallback
2. Object类型的state对象
3. 等待多久开始执行,如果设置为0则马上执行
4. 每次执行的时间间隔
这个Timer的回调函数在线程池中执行
没有静态方法,就两个实例方法Change和Dispose.
没法设置Start, Stop....很不方便,new 完之后直接开始干活。
MSDN:
As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.
推荐用System.Timers.Timer,这个要方便得多
下面是一个简单的样例:
class Program
{
static void Main(string[] args)
{
MyState state = new MyState();
Timer x = null;
x = new Timer(delegate(object o)
{
if (state.Counter == 3)//只运行3次
{
Console.WriteLine("3 times only!");
x.Dispose();
return;
}
MyState s = o as MyState;
s.Counter++;
Console.WriteLine("do");
}, state, 2000, 1000);
Console.ReadKey();
}
}
class MyState
{
public int Counter;
}
{
static void Main(string[] args)
{
MyState state = new MyState();
Timer x = null;
x = new Timer(delegate(object o)
{
if (state.Counter == 3)//只运行3次
{
Console.WriteLine("3 times only!");
x.Dispose();
return;
}
MyState s = o as MyState;
s.Counter++;
Console.WriteLine("do");
}, state, 2000, 1000);
Console.ReadKey();
}
}
class MyState
{
public int Counter;
}