123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- using System;
- using System.Threading;
- namespace Wayne.Lib
- {
-
-
-
- public class WayneTimerFactory : ITimerFactory
- {
-
-
-
-
-
-
-
- public ITimer Create(int id, IIdentifiableEntity parentEntity, string name)
- {
- return new WayneTimer(id, parentEntity, name);
- }
-
-
-
-
-
-
-
-
-
- public ITimer<TState> Create<TState>(int id, IIdentifiableEntity parentEntity, string name, TState state)
- {
- return new WayneTimer<TState>(id, parentEntity, name, state);
- }
- }
-
-
-
- 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"; } }
-
-
-
- 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<TState> : WayneTimerChanger, ITimer<TState>
- {
- public WayneTimer(int id, IIdentifiableEntity parentEntity, string name, TState state)
- : base(id, parentEntity, name, state)
- {
- }
- public event EventHandler<EventArgs<TState>> OnTimeout;
- protected override void TimerCallback(object state)
- {
- OnTimeout.Fire(this, new EventArgs<TState>((TState)state));
- }
- }
- }
|