简易延时器(未测试)

一般都会用System.Threading.Thread.Sleep来进行“等待”操作,但我总感觉用起来“有点卡”。于是乎我自己写了个,鉴于这文章也不会有几个人看,我就只在控制台程序做了简单的测试,先贴出来算是个记录吧。


我用的是System.Threading.Timer来做的延时计时器,先把Timer包装进一个TimeState类:

    public class TimerState<T> : IDisposable
    {
        public Timer Timer { get; set; }
        public T Data { get; set; }

        public TimerState()
        {

        }

        public TimerState(Timer timer, T data)
        {
            this.Timer = timer;
            this.Data = data;
        }

        public void Dispose()
        {
            if (this.Timer != null)
            {
                this.Timer.Dispose();
            }
        }
    }

然后用 System.Threading.ManualResetEvent 进行“等待”操作:

    public class Delayer
    {
        public static void Wait(int millisecondsTimeout)
        {
            if (millisecondsTimeout > 0)
            {
                TimerState<ManualResetEvent> state = new TimerState<ManualResetEvent>();
                Timer timer = new Timer(Delayer.WaitHandler, state, -1, -1);
                state.Timer = timer;
                ManualResetEvent blocker = new ManualResetEvent(false);
                state.Data = blocker;
                blocker.Reset();
                state.Timer.Change(millisecondsTimeout, -1);
                blocker.WaitOne();
            }
        }

        private static void WaitHandler(object obj)
        {
            try
            {
                TimerState<ManualResetEvent> state = (TimerState<ManualResetEvent>)obj;
                if (state != null)
                {
                    if (state.Data != null)
                    {
                        state.Data.Set();
                        state.Data.Dispose();
                    }
                    state.Dispose();
                }
            }
            catch
            {
                throw;
            }
        }
    }
代码简单,不用多说了就。

看了下Thread.Sleep,发现还有一个重载,于是乎在强迫症的作用下加上去:

        public static void Wait(TimeSpan timeout)
        {
            Delayer.Wait((int)timeout.TotalMilliseconds);
        }


有兴趣的可以拿去用,顺便帮测测。


也许有人早就写过了,但我这个确实是自己搞出来的。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值