/
DefaultScheduler.cs
198 lines (167 loc) · 8.07 KB
/
DefaultScheduler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Reactive.Disposables;
namespace System.Reactive.Concurrency
{
/// <summary>
/// Represents an object that schedules units of work on the platform's default scheduler.
/// </summary>
/// <seealso cref="Scheduler.Default">Singleton instance of this type exposed through this static property.</seealso>
public sealed class DefaultScheduler : LocalScheduler, ISchedulerPeriodic
{
private sealed class UserWorkItem<TState> : IDisposable
{
private IDisposable _cancelRunDisposable;
private IDisposable _cancelQueueDisposable;
private readonly TState _state;
private readonly IScheduler _scheduler;
private readonly Func<IScheduler, TState, IDisposable> _action;
public UserWorkItem(IScheduler scheduler, TState state, Func<IScheduler, TState, IDisposable> action)
{
_state = state;
_action = action;
_scheduler = scheduler;
}
public void Run()
{
if (!Disposable.GetIsDisposed(ref _cancelRunDisposable))
{
Disposable.TrySetSingle(ref _cancelRunDisposable, _action(_scheduler, _state));
}
}
public IDisposable CancelQueueDisposable
{
get => Disposable.GetValue(ref _cancelQueueDisposable);
set => Disposable.TrySetSingle(ref _cancelQueueDisposable, value);
}
public void Dispose()
{
Disposable.TryDispose(ref _cancelQueueDisposable);
Disposable.TryDispose(ref _cancelRunDisposable);
}
}
private static readonly Lazy<DefaultScheduler> s_instance = new Lazy<DefaultScheduler>(() => new DefaultScheduler());
private static IConcurrencyAbstractionLayer s_cal = ConcurrencyAbstractionLayer.Current;
/// <summary>
/// Gets the singleton instance of the default scheduler.
/// </summary>
public static DefaultScheduler Instance => s_instance.Value;
private DefaultScheduler()
{
}
/// <summary>
/// Schedules an action to be executed.
/// </summary>
/// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
/// <param name="state">State passed to the action to be executed.</param>
/// <param name="action">Action to be executed.</param>
/// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var workItem = new UserWorkItem<TState>(this, state, action);
workItem.CancelQueueDisposable = s_cal.QueueUserWorkItem(
closureWorkItem => ((UserWorkItem<TState>)closureWorkItem).Run(),
workItem);
return workItem;
}
/// <summary>
/// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
/// </summary>
/// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
/// <param name="state">State passed to the action to be executed.</param>
/// <param name="action">Action to be executed.</param>
/// <param name="dueTime">Relative time after which to execute the action.</param>
/// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var dt = Scheduler.Normalize(dueTime);
if (dt.Ticks == 0)
return Schedule(state, action);
var workItem = new UserWorkItem<TState>(this, state, action);
workItem.CancelQueueDisposable = s_cal.StartTimer(
closureWorkItem => ((UserWorkItem<TState>)closureWorkItem).Run(),
workItem,
dt);
return workItem;
}
/// <summary>
/// Schedules a periodic piece of work, using a System.Threading.Timer object.
/// </summary>
/// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
/// <param name="state">Initial state passed to the action upon the first iteration.</param>
/// <param name="period">Period for running the work periodically.</param>
/// <param name="action">Action to be executed, potentially updating the state.</param>
/// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
{
if (period < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(period));
if (action == null)
throw new ArgumentNullException(nameof(action));
var state1 = state;
var gate = new AsyncLock();
var cancel = s_cal.StartPeriodicTimer(() =>
{
gate.Wait(() =>
{
state1 = action(state1);
});
}, period);
return Disposable.Create(() =>
{
cancel.Dispose();
gate.Dispose();
action = Stubs<TState>.I;
});
}
/// <summary>
/// Discovers scheduler services by interface type.
/// </summary>
/// <param name="serviceType">Scheduler service interface type to discover.</param>
/// <returns>Object implementing the requested service, if available; null otherwise.</returns>
protected override object GetService(Type serviceType)
{
if (serviceType == typeof(ISchedulerLongRunning))
{
if (s_cal.SupportsLongRunning)
{
return LongRunning.Instance;
}
}
return base.GetService(serviceType);
}
private sealed class LongRunning : ISchedulerLongRunning
{
public static ISchedulerLongRunning Instance = new LongRunning();
public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var cancel = new BooleanDisposable();
DefaultScheduler.s_cal.StartThread(
arg =>
{
var d = (ICancelable)arg;
//
// Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
// requires us to ensure the scheduled work gets an opportunity to observe
// the cancellation request.
//
action(state, d);
},
cancel
);
return cancel;
}
}
}
}