C# CheckStatus()方法

    这里介绍C# CheckStatus()方法,以及介绍调用Timer.Dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。

    C#语言还是比较常见的东西,这里我们主要介绍C# CheckStatus()方法,包括介绍设置一个定时器,定时执行用户指定的函数等方面。

    Timer类:设置一个定时器,定时执行用户指定的函数。

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

    1. Timer timer = new Timer(timerDelegate, s,1000, 1000);  
    2. // 第一个参数:指定了TimerCallback 委托,表示要执行的方法;  
    3. // 第二个参数:一个包含回调方法要使用的信息的对象,或者为空引用;  
    4. // 第三个参数:延迟时间——计时开始的时刻距现在的时间,单位是毫秒,
      指定为“0”表示立即启动计时器;  
    5. // 第四个参数:定时器的时间间隔——计时开始以后,每隔这么长的一段时间,
      TimerCallback所代表的方法将被调用一次,单位也是毫秒。
      指定 Timeout.Infinite 可以禁用定期终止。 

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

    Timer类的程序示例:

    1. using System;  
    2. using System.Threading;  
    3.  
    4. namespace ThreadExample  
    5. {  
    6. class TimerExampleState   
    7. {  
    8. public int counter = 0;   
    9. public Timer tmr;  
    10. }  
    11.  
    12. class App   
    13. {  
    14. public static void Main()  
    15. {  
    16. TimerExampleState s = new TimerExampleState();   
    17.  
    18. //创建代理对象TimerCallback,该代理将被定时调用  
    19. TimerCallback timerDelegate = new TimerCallback(CheckStatus);   
    20.  
    21. //创建一个时间间隔为1s的定时器  
    22. Timer timer = new Timer(timerDelegate, s,1000, 1000);   
    23.  s.tmr = timer;   
    24.  
    25. //主线程停下来等待Timer对象的终止  
    26. while(s.tmr != null)  
    27. Thread.Sleep(0);  
    28. Console.WriteLine("Timer example done.");  
    29. Console.ReadLine();  
    30. }  
    31.  
    32. //下面是被定时调用的方法  
    33. static void CheckStatus(Object state)  
    34. {  
    35. TimerExampleState s =(TimerExampleState)state;   
    36. s.counter++;  
    37. Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);  
    38.  
    39. if(s.counter == 5)   
    40. {  
    41. //使用Change方法改变了时间间隔  
    42. (s.tmr).Change(10000,2000);  
    43. Console.WriteLine("changed");  
    44. }  
    45.  
    46. if(s.counter == 10)   
    47. {  
    48. Console.WriteLine("disposing of timer");  
    49. s.tmr.Dispose();  
    50.  s.tmr = null;  
    51. }  
    52. }  
    53. }  

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

原文地址:https://www.cnblogs.com/zcy_soft/p/1773629.html