码迷,mamicode.com
首页 > 其他好文 > 详细

C# 控制台上的自制Timer

时间:2014-07-25 00:02:14      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:style   http   os   strong   2014   art   for   re   

一、关于本文

本文实现了类TimerTest,该类可以模拟一个Timer,经过指定时间间隔执行某个事件。

二、TimerTest类

//定时器类
class TimerTest
{
    //线程名
    string _ThreadName;
    public string ThreadName
    {
        get { return _ThreadName; }
        private set { _ThreadName = value; }
    }

    //时间间隔
    int _TimeInterval;
    public int TimeInterval
    {
        get { return _TimeInterval; }
        set { _TimeInterval = value; }
    }

    //当前计时器是否启用 true:启用 false:不启用
    bool _Enabled;
    public bool Enabled
    {
        get { return _Enabled; }
        set { _Enabled = value; }
    }

    //每隔一段时间需要运行的事件
    public delegate void TickEventHandler();
    public event TickEventHandler TickEvent;

    /// <summary>
    /// 建立一个计时器(构造函数)
    /// </summary>
    /// <param name="ThreadName">线程名</param>
    /// <param name="TimeInterval">时间间隔</param>
    public TimerTest(string ThreadName, int TimeInterval = int.MaxValue)
    {
        this.ThreadName = ThreadName;
        this.TimeInterval = TimeInterval;
        this.Enabled = false;
    }

    /// <summary>
    /// 定期执行事件
    /// </summary>
    public void Run()
    {
        while (true)
        {
            //如果当前计时器并未启用,则每隔一段时间检测是否被启用
            if (!this.Enabled)
            {
                Thread.Sleep(100);
                continue;
            }

            //触发事件TickEvent
            if (TickEvent != null)
            {
                TickEvent();
            }

            //休眠一定的时间,等待下一个循环
            Thread.Sleep(TimeInterval % 100);
            for (int temp = 0; temp < TimeInterval / 100; temp++)
            {
                Thread.Sleep(100);
                if (!this.Enabled)
                {
                    break;
                }
            }
        }
    }
}

三、调用示例

每1000毫秒输出当前的时间
/// <summary>
/// 测试用事件
/// </summary>
static void TestHandler()
{
    //TODO
    Console.WriteLine(DateTime.Now.ToLongTimeString());
}

static void Main(string[] args)
{
    TimerTest tt = new TimerTest("timer_test", 1000);
    tt.Enabled = true;
    tt.TickEvent += TestHandler;

    Thread timer = new Thread(tt.Run);
    timer.Start();
            
    Console.ReadLine();
}

四、运行结果

bubuko.com,布布扣

END

C# 控制台上的自制Timer,布布扣,bubuko.com

C# 控制台上的自制Timer

标签:style   http   os   strong   2014   art   for   re   

原文地址:http://my.oschina.net/Tsybius2014/blog/294631

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!