Guest User

Updater refactor

a guest
Sep 27th, 2015
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using System;
  2. using System.Timers;
  3.  
  4. namespace ProcessShredder.Updating
  5. {
  6.     public interface IUpdate
  7.     {
  8.         /// <summary>
  9.         /// A method used to update parts of your object.
  10.         /// When used with GUIs or thread sensative objects
  11.         /// you should invoke their thread to run code
  12.         /// </summary>
  13.         void TimedUpdate();
  14.     }
  15.  
  16.     public class Updater
  17.     {
  18.         /// <summary>The object being updated</summary>
  19.         public IUpdate Obj { get; set; }
  20.  
  21.         /// <summary>The time between update events</summary>
  22.         public int Interval { get; set; }
  23.  
  24.         private Timer timer = null;
  25.  
  26.         /// <summary>Sends timed update messages to IUpdate classes</summary>
  27.         /// <param name="obj">The object to update</param>
  28.         public Updater(IUpdate obj)
  29.         {
  30.             Obj = obj;
  31.         }
  32.  
  33.         /// <summary>Begins sending update messages</summary>
  34.         /// <param name="interval">Frequency in milliseconds</param>
  35.         /// <returns>true if the operation was a success, false otherwise</returns>
  36.         public bool StartTimedUpdates(int interval)
  37.         {
  38.             if (interval > 0)
  39.             {
  40.                 Interval = interval;
  41.                 timer = new Timer(interval);
  42.                 timer.Elapsed += OnTimedEvent;
  43.                 timer.AutoReset = false;
  44.                 timer.Enabled = true;
  45.                 return true;
  46.             }
  47.             return false;
  48.         }
  49.        
  50.         /// <summary>
  51.         /// Called every 'Interval' milliseconds after StarTimedUpdates
  52.         /// succeeds; calls TimedUpdate() for the stored object
  53.         /// </summary>
  54.         private void OnTimedEvent(Object source, ElapsedEventArgs e)
  55.         {
  56.             if (Obj != null)
  57.             {
  58.                 Obj.TimedUpdate();
  59.             }
  60.  
  61.             if (timer != null)
  62.             {
  63.                 timer.Interval = Interval;
  64.             }
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment