关于AutoResetEvent、TimeSpan

有点明白了,赶紧记下来。

using System;

using System.Threading;



class TimerExample

{

    static void Main()

    {

       // AutoResetEvent类的作用就在于可以让等待的线程继续

	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);



        TimeSpan delayTime = new TimeSpan(0, 0, 2);//两秒的时间

        TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);//1/4秒的时间



        // 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, delayTime, intervalTime);//这个timer在开始调用timerDelegate之前停留delayTime长的时间,并每隔intervalTime长的时间重新调用一次。autoEvent这个参数很关键,当timerDelegate被调用时,就是调用的参数,可以被执行的函数所用

        Console.WriteLine("********开始了*********");

        // When autoEvent signals, change the period to every 

        // 1/2 second.

        autoEvent.WaitOne(3000, false);//这里进程会停留一段时间,比如这里设定的3秒。在这3秒内,stateTimer 将发挥其作用,不断的调用timerDelegate。但是,这里只有3秒的时间让其发挥,超过三秒后,进程会继续往下执行,stateTimer 会被重新设定。当然,如果这里停留的时间够长,长到足够stateTimer 发挥完其作用,直到timerDelegate会强制进程继续从而改变stateTimer 

        stateTimer.Change(new TimeSpan(0),

            intervalTime + intervalTime);

        Console.WriteLine("\nChanging period.\n");



        // When autoEvent signals the second time, dispose of 

        // the timer.

        autoEvent.WaitOne(50000, false);

        stateTimer.Dispose();

        Console.WriteLine("\nDestroying timer.");

        Console.ReadLine();

    }

}



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,2}.",

            DateTime.Now.ToString("h:mm:ss.fff"),

            (++invokeCount).ToString());



        if (invokeCount == maxCount)

        {

            // Reset the counter and signal Main.

            invokeCount = 0;

            autoEvent.Set();

        }

    }

}



你可能感兴趣的:(event)