andrew4582

Timer Service Base Class

Jan 21st, 2015
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 3.91 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Threading;
  6.  
  7. namespace Common.Services
  8. {
  9.  
  10.     //Example:
  11.     /*
  12.     public class YourTimerService : TimerServiceBase
  13.     {
  14.         protected override void OnTimerInterval(object state)
  15.         {
  16.             Console.WriteLine("OnTimerInterval called!");
  17.         }
  18.     }
  19.     */
  20.  
  21.     /// <summary>
  22.     /// Base class that uses a timer to execute functionality
  23.     /// </summary>
  24.     public abstract class TimerServiceBase : IDisposable
  25.     {
  26.         readonly Timer _pollTimer;
  27.  
  28.         public TimeSpan Interval { get; protected set; }
  29.  
  30.         public bool IsStarted { get; protected set; }
  31.  
  32.         public TimerServiceBase(object state = null)
  33.             : this(5000, state) { }
  34.  
  35.         public TimerServiceBase(int intervalMilliseconds, object state = null)
  36.             : this(TimeSpan.FromMilliseconds(intervalMilliseconds), state) { }
  37.  
  38.         public TimerServiceBase(TimeSpan interval, object state = null)
  39.         {
  40.             this.Interval = interval;
  41.             _pollTimer = new Timer(OnTimerInterval, state, Timeout.Infinite, Timeout.Infinite);
  42.         }
  43.  
  44.         /// <summary>
  45.         /// Called when the underlying timer is executed
  46.         /// </summary>
  47.         /// <param name="state">Optional state passed in via the ctor</param>
  48.         protected abstract void OnTimerInterval(object state);
  49.  
  50.         /// <summary>
  51.         /// Starts the underlying timer
  52.         /// </summary>
  53.         /// <param name="args">Optional arguments</param>
  54.         public void Start(params string[] args)
  55.         {
  56.             Start(TimeSpan.FromSeconds(0), args);
  57.         }
  58.  
  59.         /// <summary>
  60.         /// Starts the underlying timer
  61.         /// </summary>
  62.         /// <param name="delay">A <see cref="T:System.TimeSpan"/> representing the amount of time to delay before invoking the OnTimerInterval method</param>
  63.         /// <param name="args">Optional arguments</param>
  64.         public void Start(TimeSpan dueTime, params string[] args)
  65.         {
  66.             if (IsStarted)
  67.                 throw new InvalidOperationException("Service already started!");
  68.  
  69.             if (!OnStart(args))
  70.                 return;
  71.  
  72.             IsStarted = true;
  73.             _pollTimer.Change(dueTime, Interval);
  74.         }
  75.  
  76.         /// <summary>
  77.         /// Called when the Start() method is called. Return true to continue to start the service otherwise false
  78.         /// </summary>
  79.         /// <param name="args">Optional arguments passed in from the Start() method</param>
  80.         /// <returns>True to continue to start the service otherwise false</returns>
  81.         protected virtual bool OnStart(string[] args)
  82.         {
  83.             return true;
  84.         }
  85.  
  86.         /// <summary>
  87.         /// Stops the underlying timer from calling the OnTimerInterval method
  88.         /// </summary>
  89.         public void Stop()
  90.         {
  91.             if (!IsStarted)
  92.                 throw new InvalidOperationException("Service already stopped!");
  93.             if (!OnStop())
  94.                 return;
  95.  
  96.             IsStarted = false;
  97.             _pollTimer.Change(Timeout.Infinite, Timeout.Infinite);
  98.         }
  99.  
  100.         /// <summary>
  101.         /// Called when the Stop() method is called. Return true to continue to stop the service otherwise false to cancel the stopping operation
  102.         /// </summary>
  103.         /// <returns>True to continue to stop the service otherwise false</returns>
  104.         protected virtual bool OnStop()
  105.         {
  106.             return true;
  107.         }
  108.  
  109.         #region IDisposable Pattern
  110.  
  111.         protected bool IsDisposed { get; private set; }
  112.  
  113.         [System.Diagnostics.DebuggerStepThrough]
  114.         protected void EnsureNotDisposed()
  115.         {
  116.             if (IsDisposed)
  117.                 throw new ObjectDisposedException(GetType().Name);
  118.         }
  119.  
  120.         [System.Diagnostics.DebuggerStepThrough]
  121.         public virtual void Dispose()
  122.         {
  123.             if (IsDisposed)
  124.                 throw new ObjectDisposedException(this.GetType().Name);
  125.             try
  126.             {
  127.                 this.Dispose(true);
  128.             }
  129.             finally
  130.             {
  131.                 GC.SuppressFinalize(this);
  132.             }
  133.         }
  134.  
  135.         [System.Diagnostics.DebuggerStepThrough]
  136.         protected virtual void Dispose(bool disposing)
  137.         {
  138.             try
  139.             {
  140.                 if (disposing && !IsDisposed)
  141.                 {
  142.                     //Do object cleanup here
  143.                     _pollTimer.Change(Timeout.Infinite, Timeout.Infinite);
  144.                     _pollTimer.Dispose();
  145.                 }
  146.             }
  147.             finally
  148.             {
  149.                 this.IsDisposed = true;
  150.             }
  151.         }
  152.         #endregion
  153.     }
  154. }
Advertisement
Add Comment
Please, Sign In to add comment