Timer in Portable Library

后端 未结 6 885
我寻月下人不归
我寻月下人不归 2020-11-29 03:41

I can\'t find a timer in portable library / Windows Store. (Targeting .net 4.5 and Windows Store aka Metro)

Does any have an idea on how to created some kind of timi

6条回答
  •  悲哀的现实
    2020-11-29 04:00

    Following suggestion #3 from David Kean, here's my hacky Timer adapter - put this in a PCL library that targets .net 4.0, and reference it from 4.5:

        public class PCLTimer
        {
            private Timer _timer;
    
            private Action _action;
    
            public PCLTimer(Action action, TimeSpan dueTime, TimeSpan period)
            {
                _action = action;
    
                _timer = new Timer(PCLTimerCallback, null, dueTime, period);           
            }
    
            private void PCLTimerCallback(object state)
            {
                _action.Invoke();
            }
    
            public bool Change(TimeSpan dueTime, TimeSpan period)
            {
                return _timer.Change(dueTime, period);
            }
        }
    

    And then to use it, you can do this from your 4.5 PCL library:

        private void TimeEvent()
        {            
            //place your timer callback code here
        }
    
        public void SetupTimer()
        {            
            //set up timer to run every second
            PCLTimer _pageTimer = new PCLTimer(new Action(TimeEvent), TimeSpan.FromMilliseconds(-1), TimeSpan.FromSeconds(1));
    
            //timer starts one second from now
            _pageTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    
        }
    

提交回复
热议问题