comparison Implab/Components/PollingComponent.cs @ 258:d0876436d95d v3

missing file
author cin
date Fri, 13 Apr 2018 00:44:57 +0300
parents
children 7d52dc684bbd
comparison
equal deleted inserted replaced
257:440801d88019 258:d0876436d95d
1 using System;
2 using System.Threading;
3 using System.Threading.Tasks;
4
5 namespace Implab.Components {
6 public abstract class PollingComponent : RunnableComponent {
7
8 readonly Timer m_timer;
9
10 readonly CancellationTokenSource m_cancellation = new CancellationTokenSource();
11
12 /// <summary>
13 /// Poll interval in milliseconds.
14 /// </summary>
15 /// <returns></returns>
16 public int Interval { get; set; }
17
18 /// <summary>
19 /// Delay to the first poll after start in milliseconds
20 /// </summary>
21 /// <returns></returns>
22 public int Delay { get; set; }
23
24 /// <summary>
25 /// Indicates how to handle unhandled exceptions in <see cref="Poll()"/> method.
26 /// </summary>
27 /// <returns></returns>
28 public bool FailOnError { get; set; }
29
30 /// <summary>
31 /// Event for the unhandled exceptions in <see cref="Poll()"/> method.
32 /// </summary>
33 public event EventHandler<UnhandledExceptionEventArgs> UnhandledException;
34
35 protected PollingComponent(bool initialized) : base(initialized) {
36 m_timer = new Timer(OnTimer);
37 }
38
39 protected override void RunInternal() {
40 ScheduleNextPoll(Delay);
41 }
42
43
44 //TODO override stop
45
46 protected abstract Task Poll(CancellationToken ct);
47
48 void ScheduleNextPoll(int timeout) {
49 lock (SynchronizationObject) {
50 if (State == ExecutionState.Running)
51 m_timer.Change(timeout, Timeout.Infinite);
52 }
53 }
54
55 void OnTimer(object state) {
56 try {
57 Poll(m_cancellation.Token);
58 } catch (Exception e) {
59 UnhandledException.DispatchEvent(this, new UnhandledExceptionEventArgs(e, false));
60 if (FailOnError)
61 Fail(e);
62 }
63 ScheduleNextPoll(Interval);
64 }
65
66 protected override void Dispose(bool disposing) {
67 if (disposing)
68 Safe.Dispose(m_timer, m_cancellation);
69 base.Dispose(disposing);
70 }
71
72 }
73 }