using System; using System.Threading; namespace Wayne.Lib { /// /// Timer factory /// public class WayneTimerFactory : ITimerFactory { /// /// Creates a timer /// /// /// /// /// public ITimer Create(int id, IIdentifiableEntity parentEntity, string name) { return new WayneTimer(id, parentEntity, name); } /// /// Creates a timer /// /// /// /// /// /// /// public ITimer Create(int id, IIdentifiableEntity parentEntity, string name, TState state) { return new WayneTimer(id, parentEntity, name, state); } } /// /// Changes the due time and interval of a timer. /// internal abstract class WayneTimerChanger : ITimerChanger { private bool disposed; private readonly Timer timer; protected WayneTimerChanger(int id, IIdentifiableEntity parentEntity, string name, object state) { Id = id; ParentEntity = parentEntity; EntitySubType = name; timer = new Timer(TimerCallback, state, Timeout.Infinite, Timeout.Infinite); } ~WayneTimerChanger() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) return; disposed = true; if (disposing) timer.Dispose(); } public int Id { get; private set; } public string EntityType { get { return "WayneTimer"; } } /// /// This is used by the logger and should never be set by inheriting classes /// public string FullEntityName { get; set; } public string EntitySubType { get; private set; } public IIdentifiableEntity ParentEntity { get; private set; } public bool Change(TimeSpan? dueTime, TimeSpan? period) { if (!dueTime.HasValue || !period.HasValue) { return timer.Change(dueTime.HasValue ? (long)dueTime.Value.TotalMilliseconds : Timeout.Infinite, period.HasValue ? (long)period.Value.TotalMilliseconds : Timeout.Infinite); } return timer.Change(dueTime.Value, period.Value); } protected abstract void TimerCallback(object state); } internal class WayneTimer : WayneTimerChanger, ITimer { public WayneTimer(int id, IIdentifiableEntity parentEntity, string name) : base(id, parentEntity, name, null) { } public event EventHandler OnTimeout; protected override void TimerCallback(object state) { OnTimeout.Fire(this, EventArgs.Empty); } } internal class WayneTimer : WayneTimerChanger, ITimer { public WayneTimer(int id, IIdentifiableEntity parentEntity, string name, TState state) : base(id, parentEntity, name, state) { } public event EventHandler> OnTimeout; protected override void TimerCallback(object state) { OnTimeout.Fire(this, new EventArgs((TState)state)); } } }