System.Threading.Timer

这个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;
}

转载于:https://www.cnblogs.com/teamleader/archive/2011/02/15/1955410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值