C#多线程——Timer

来源:互联网 发布:网络节点半径 编辑:程序博客网 时间:2024/06/07 20:38

每隔一定的时间,触发去做指定的事情,可以用timer类。

Timer timer = new Timer(timerDelegate, ParamObject, 1000, 1000)    其中,

1、第一个参数是要执行的方法

2、第二个参数是回调方法要使用的对象信息;

3、第三个参数是延时启动的时间间隔,“0”表示立即启动;

4、第四个参数是Timer的Interval。

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Threading;  
  5. using System.Collections;  
  6.   
  7. namespace Demo  
  8. {  
  9.     class ParamObject  
  10.     {  
  11.         public int iCounter = 0;  
  12.         public Timer aTimer;  
  13.     }  
  14.   
  15.     class Program  
  16.     {  
  17.        public static void Main(string[] args)  
  18.        {  
  19.            ParamObject aParamObject = new ParamObject();  
  20.            Timer aTimer = new Timer(new TimerCallback(CheckStatus), aParamObject, 1000, 1000);  
  21.            aParamObject.aTimer = aTimer;  
  22.   
  23.            while (aParamObject.aTimer != null)  
  24.            {  
  25.                Thread.Sleep(0);  
  26.            }  
  27.            Console.ReadLine();  
  28.        }  
  29.   
  30.         static void CheckStatus(object paramObject)  
  31.         {  
  32.             ParamObject aParamObject = (ParamObject)paramObject;  
  33.             aParamObject.iCounter++;  
  34.             Console.WriteLine("{0} status: {1}", DateTime.Now.TimeOfDay, aParamObject.iCounter);  
  35.   
  36.             if (aParamObject.iCounter == 5)  
  37.             {  
  38.                 // Wait 1000 ms and go on to do the timer event  
  39.                 aParamObject.aTimer.Change(1000, 2000);  
  40.                 Console.WriteLine("Timer interval changed!");  
  41.             }  
  42.   
  43.             if (aParamObject.iCounter == 10)  
  44.             {  
  45.                 Console.WriteLine("Dispose timer");  
  46.                 aParamObject.aTimer.Dispose();  
  47.                 aParamObject.aTimer = null;  
  48.             }  
  49.         }  
  50.     }  
  51. }  
0 0
原创粉丝点击