C#多线程学习(五) 多线程的自动管理(定时器) (转载)

本文来自互联网

 

Timer类:设置一个定时器,定时执行用户指定的函数。
              定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数。

初始化一个Timer对象:
Timer timer = new Timer(timerDelegate, s,1000, 1000);

// 第一个参数:指定了TimerCallback 委托,表示要执行的方法;
// 第二个参数:一个包含回调方法要使用的信息的对象,或者为空引用;

// 第三个参数:延迟时间——计时开始的时刻距现在的时间,单位是毫秒,指定为“0”表示立即启动计时器;
// 第四个参数:定时器的时间间隔——计时开始以后,每隔这么长的一段时间,TimerCallback所代表的方法将被调用一次,单位也是毫秒。指定 Timeout.Infinite 可以禁用定期终止。

Timer.Change()方法:修改定时器的设置。(这是一个参数类型重载的方法)
使用示例:  timer.Change(1000,2000);


Timer类的程序示例(来源:MSDN):

using  System;
using
 System.Threading;

namespace
 ThreadExample
{
    
class
 TimerExampleState 
    {
      
public int counter = 0
;
      
public
 Timer tmr;
    }

    
class
 App 
    {
      
public static void
 Main()
      {
          TimerExampleState s 
= new
 TimerExampleState();

          
//创建代理对象TimerCallback,该代理将被定时调用

          TimerCallback timerDelegate = new  TimerCallback(CheckStatus);

            
//创建一个时间间隔为1s的定时器

            Timer timer = new Timer(timerDelegate, s,10001000 );
            s.tmr 
=
 timer;

            
//主线程停下来等待Timer对象的终止

            while(s.tmr != null )
            Thread.Sleep(
0
);
            Console.WriteLine(
"Timer example done."
);
            Console.ReadLine();
      }

      
//下面是被定时调用的方法

      static void  CheckStatus(Object state)
      {
            TimerExampleState s 
=
(TimerExampleState)state;
            s.counter
++
;
            Console.WriteLine(
"{0} Checking Status {1}."
,DateTime.Now.TimeOfDay, s.counter);

            
if(s.counter == 5
)
            {
                
//使用Change方法改变了时间间隔

                (s.tmr).Change(10000,2000 );
                Console.WriteLine(
"changed"
);
            }

            
if(s.counter == 10
)
            {
                Console.WriteLine(
"disposing of timer"
);
                s.tmr.Dispose();
                s.tmr 
= null
;
            }
      }
    }
}

 

version2

using System;
using System.Threading;
using System.Collections;

namespace ThreadExample
{
    class App
    {
        public static void Main()
        {
            TimerExampleState s = new TimerExampleState();
            TimerCallback timerDelegate = new TimerCallback(s.CheckStatus);

            Timer timer = new Timer(timerDelegate, null, 1000, 1000);
            s.tmr = timer;

            while (s.tmr != null)
                Thread.Sleep(0);
            Console.WriteLine("Timer example done./n");
            Console.ReadLine();
        }

    }

    class TimerExampleState
    {
        public int counter = 0;
        public Timer tmr;

        public void CheckStatus(object stateInfo)
        {
            Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, ++counter);

            if (counter == 5)
            {
                tmr.Change(5000, 2000);
                Console.WriteLine("/nchanged/n");
            }

            if (counter == 10)
            {
                Console.WriteLine("/ndisposing of timer/n");
                tmr.Dispose();
                tmr = null;
            }
        }
    }
}

 

  程序首先创建了一个定时器,它将在创建1秒之后开始每隔1秒调用一次CheckStatus()方法,当调用5次以后,在CheckStatus()方法中修改了时间间隔为2秒,并且指定在10秒后重新开始。当计数达到10次,调用Timer.Dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。

 

执行结果如下:

 

补充:

补充关于timer的实例(来自msdn),以加深对其用法的理解

using System;
using System.Threading;
using System.Collections;

namespace ThreadExample
{

    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
            // second.
            autoEvent.WaitOne(3500, false);
            stateTimer.Change(0, 1000);
            Console.WriteLine("/nChanging period./n");

 

            // When autoEvent signals the second time, dispose of
            // the timer.
            autoEvent.WaitOne(10000, false);
            stateTimer.Dispose();
            Console.WriteLine("/nDestroying timer.");
            Console.Read();
        }
    }

    class StatusChecker
    {
        int invokeCount, maxCount;

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

        public void CheckStatus(Object stateInfo)
        {
            AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
            Console.WriteLine("{0} Checking status {1,2}.",
                DateTime.Now.ToString("h:mm:ss.fff"), (++this.invokeCount).ToString());

            if (this.invokeCount == this.maxCount)
            {
                this.invokeCount = 0;
                autoEvent.Set();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值