Auto status change to "Under Review"
@@ -0,0 +1,73 | |||||
|
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 | } No newline at end of file |
General Comments 3
ok, latest stable version should be in default
You need to be logged in to leave comments.
Login now