Timer简单使用

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent = new AutoResetEvent(false);
        StatusChecker statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate =
            new TimerCallback(statusChecker.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n",
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer =
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        //autoEvent.Set();  //获得了信息量,终止进程阻塞
        autoEvent.WaitOne(10000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");
        autoEvent.WaitOne(10000, false);

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(10000, false);          //一次WaitOne需要重新获取信息量
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1}.  CurrentThreadID:{2}",
            DateTime.Now.ToString("h:mm:ss.fff"),
            (++invokeCount).ToString(), Thread.CurrentThread.ManagedThreadId);

        if (invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值