尔冬橙

博客园 首页 新随笔 联系 订阅 管理

在线程中,如果要暂停一定的时间,可以使用Thread的Sleep方法,让线程暂停。在微软新的win8API中,已经

用Task来实现原来用线程实现的许多功能,同样,Task也有Delay方法,让程序暂停一定的时间。

以下程序利用System.Threading.Timer让程序每隔间隔的时间执行回调方法:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TimerApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Working with Timer type *****/n");

            // Create the delegate for the Timer type.   
            TimerCallback timeCB = new TimerCallback(PrintTime);

            // Establish timer settings.   
            Timer t = new Timer(
              timeCB,             // The TimerCallback delegate type.   
              "Hello From Main",  // Any info to pass into the called method (null for no info).   
              5000,                  // Amount of time to wait before starting.   
              Timeout.Infinite);   //一秒钟调用一次 Interval of time between calls (in milliseconds).   

            Console.WriteLine("Hit key to terminate...");
            Console.ReadLine();
        }

        static void PrintTime(object state)
        {
            Console.WriteLine("Time is: {0}, Param is: {1}",
              DateTime.Now.ToLongTimeString(), state.ToString());
        }
    }
}

 如果把时间间隔1000改成 Timeout.Infinite

这样回调方法PrintTime只会在1秒之后调用一次。

除了Threading下有个Timer类之外,.net中还有另一个Timer,就是System.Timer名称空间下的Timer。

此Timer的用法和Threading下的Timer不太相同。

System.Timers.Timer t2 = new System.Timers.Timer(100);
                t2.Elapsed += t2_Elapsed;
                //t1.AutoReset = false;
                t2.Enabled = true;
            }
        }
        void t2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

        }     

 其中AutoReset属性的含义是是否在每次时间间隔到了都触发Elapsed事件还是只触发一次(t1.AutoReset = false;)。

 

 

 

posted on 2013-02-04 22:32  尔冬橙  阅读(10410)  评论(0编辑  收藏  举报