毛毛的小窝 — 关注技术交流、让我们一起成长

导航

改变计时器的回调周期

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

        
// When autoEvent signals, change the period to every 
        
// 1/2 second.(改变周期)
        autoEvent.WaitOne(5000false);
        stateTimer.Change(
01000);
        Console.WriteLine(
"\nChanging period.\n");

        
// When autoEvent signals the second time, dispose of 
        
// the timer.
        autoEvent.WaitOne(5000false);
        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();
        }

    }

}


毛毛的小窝

posted on 2007-05-16 10:24  mjgforever  阅读(221)  评论(0编辑  收藏  举报