Search code examples
timerxamarinportable-class-library

PCL Timer Change function


I had checked out Timer in Portable Library, but I had no idea how to call the Change function, because it was not implemented in the class nor inherited from parent.

_timer = new Timer(OnTimerTick, null, TimeSpan.FromSeconds(1.0), TimeSpan.Zero);
_timer.Change(TimeSpan.FromSeconds(1.0), TimeSpan.Zero); //how to implement this

Solution

  • Instead of using the 1st solution: (building the class Timer) by David Kean, I am now using his 3rd solution: (create a target .NET 4.0 Timer adapter) with the code sample by Henry C.

    Anyway, I'm still hoping to get some feedback on how to implement the Change function in the Timer class as defined in .NET. Thanks!

    public class PCLTimer
    {
        private System.Threading.Timer timer;
        private Action<object> action;
    
        public PCLTimer(Action<object> action, object state, int dueTimeMilliseconds, int periodMilliseconds)
        {
            this.action = action;
            timer = new System.Threading.Timer(PCLTimerCallback, state, dueTimeMilliseconds, periodMilliseconds);
        }
    
        public PCLTimer(Action<object> action, object state, TimeSpan dueTimeMilliseconds, TimeSpan periodMilliseconds)
        {
            this.action = action;
            timer = new System.Threading.Timer(PCLTimerCallback, state, dueTimeMilliseconds, periodMilliseconds);
        }
    
        private void PCLTimerCallback(object state)
        {
            action.Invoke(state);
        }
    
        public bool Change(int dueTimeMilliseconds, int periodMilliseconds)
        {
            return timer.Change(dueTimeMilliseconds, periodMilliseconds);
        }
    
        public bool Change(TimeSpan dueTimeMilliseconds, TimeSpan periodMilliseconds)
        {
            return timer.Change(dueTimeMilliseconds, periodMilliseconds);
        }
    
        public new void Dispose()
        {
            timer.Dispose();
        }
    }