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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if !WINDOWS && !NO_THREAD
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Threading;
namespace System.Reactive.Concurrency
{
/// <summary>
/// Represents an object that schedules units of work on the CLR thread pool.
/// </summary>
/// <seealso cref="ThreadPoolScheduler.Instance">Singleton instance of this type exposed through this static property.</seealso>
public sealed class ThreadPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
{
private static readonly ThreadPoolScheduler s_instance = new ThreadPoolScheduler();
/// <summary>
/// Gets the singleton instance of the CLR thread pool scheduler.
/// </summary>
public static ThreadPoolScheduler Instance
{
get
{
return s_instance;
}
}
ThreadPoolScheduler()
{
}
/// <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 null.</exception>
public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
var d = new SingleAssignmentDisposable();
ThreadPool.QueueUserWorkItem(_ =>
{
if (!d.IsDisposed)
d.Disposable = action(this, state);
}, null);
return d;
}
/// <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 null.</exception>
public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
var dt = Scheduler.Normalize(dueTime);
if (dt.Ticks == 0)
return Schedule(state, action);
return new Timer<TState>(this, state, dt, action);
}
/// <summary>
/// Schedules a long-running task by creating a new thread. Cancellation happens through polling.
/// </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 null.</exception>
public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
{
if (action == null)
throw new ArgumentNullException("action");
return NewThreadScheduler.Default.ScheduleLongRunning(state, action);
}
#if !NO_STOPWATCH
/// <summary>
/// Starts a new stopwatch object.
/// </summary>
/// <returns>New stopwatch object; started at the time of the request.</returns>
public override IStopwatch StartStopwatch()
{
//
// Strictly speaking, this explicit override is not necessary because the base implementation calls into
// the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
// where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
//
return new StopwatchImpl();
}
#endif
/// <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="ArgumentNullException"><paramref name="action"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than or equal to zero.</exception>
public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
{
//
// MSDN documentation states the following:
//
// "If period is zero (0) or negative one (-1) milliseconds and dueTime is positive, callback is invoked once;
// the periodic behavior of the timer is disabled, but can be re-enabled using the Change method."
//
if (period <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException("period");
if (action == null)
throw new ArgumentNullException("action");
return new PeriodicTimer<TState>(state, period, action);
}
#if USE_TIMER_SELF_ROOT
//
// See ConcurrencyAbstractionLayerImpl.cs for more information about the code
// below and its timer rooting behavior.
//
sealed class Timer<TState> : IDisposable
{
private readonly MultipleAssignmentDisposable _disposable;
private readonly IScheduler _parent;
private readonly TState _state;
private Func<IScheduler, TState, IDisposable> _action;
private volatile System.Threading.Timer _timer;
public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
_parent = parent;
_state = state;
_action = action;
_disposable = new MultipleAssignmentDisposable();
_disposable.Disposable = Disposable.Create(Stop);
// Don't want the spin wait in Tick to get stuck if this thread gets aborted.
try { }
finally
{
//
// Rooting of the timer happens through the this.Tick delegate's target object,
// which is the current instance and has a field to store the Timer instance.
//
_timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
}
}
private void Tick(object state)
{
try
{
_disposable.Disposable = _action(_parent, _state);
}
finally
{
SpinWait.SpinUntil(IsTimerAssigned);
Stop();
}
}
private bool IsTimerAssigned()
{
return _timer != null;
}
public void Dispose()
{
_disposable.Dispose();
}
private void Stop()
{
var timer = _timer;
if (timer != TimerStubs.Never)
{
_action = Nop;
_timer = TimerStubs.Never;
timer.Dispose();
}
}
private IDisposable Nop(IScheduler scheduler, TState state)
{
return Disposable.Empty;
}
}
sealed class PeriodicTimer<TState> : IDisposable
{
private TState _state;
private Func<TState, TState> _action;
private readonly AsyncLock _gate;
private volatile System.Threading.Timer _timer;
public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
{
_state = state;
_action = action;
_gate = new AsyncLock();
//
// Rooting of the timer happens through the this.Tick delegate's target object,
// which is the current instance and has a field to store the Timer instance.
//
_timer = new System.Threading.Timer(this.Tick, null, period, period);
}
private void Tick(object state)
{
_gate.Wait(() =>
{
_state = _action(_state);
});
}
public void Dispose()
{
var timer = _timer;
if (timer != null)
{
_action = Stubs<TState>.I;
_timer = null;
timer.Dispose();
_gate.Dispose();
}
}
}
#else
abstract class Timer
{
//
// Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
//
#if !NO_HASHSET
protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
#else
protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
#endif
}
sealed class Timer<TState> : Timer, IDisposable
{
private readonly MultipleAssignmentDisposable _disposable;
private readonly IScheduler _parent;
private readonly TState _state;
private Func<IScheduler, TState, IDisposable> _action;
private System.Threading.Timer _timer;
private bool _hasAdded;
private bool _hasRemoved;
public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
_disposable = new MultipleAssignmentDisposable();
_disposable.Disposable = Disposable.Create(Unroot);
_parent = parent;
_state = state;
_action = action;
_timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
lock (s_timers)
{
if (!_hasRemoved)
{
#if !NO_HASHSET
s_timers.Add(_timer);
#else
s_timers.Add(_timer, null);
#endif
_hasAdded = true;
}
}
}
private void Tick(object state)
{
try
{
_disposable.Disposable = _action(_parent, _state);
}
finally
{
Unroot();
}
}
private void Unroot()
{
_action = Nop;
var timer = default(System.Threading.Timer);
lock (s_timers)
{
if (!_hasRemoved)
{
timer = _timer;
_timer = null;
if (_hasAdded && timer != null)
s_timers.Remove(timer);
_hasRemoved = true;
}
}
if (timer != null)
timer.Dispose();
}
private IDisposable Nop(IScheduler scheduler, TState state)
{
return Disposable.Empty;
}
public void Dispose()
{
_disposable.Dispose();
}
}
abstract class PeriodicTimer
{
//
// Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
//
#if !NO_HASHSET
protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
#else
protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
#endif
}
sealed class PeriodicTimer<TState> : PeriodicTimer, IDisposable
{
private readonly AsyncLock _gate;
private TState _state;
private Func<TState, TState> _action;
private System.Threading.Timer _timer;
public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
{
_gate = new AsyncLock();
_state = state;
_action = action;
_timer = new System.Threading.Timer(Tick, null, period, period);
lock (s_timers)
{
#if !NO_HASHSET
s_timers.Add(_timer);
#else
s_timers.Add(_timer, null);
#endif
}
}
private void Tick(object state)
{
_gate.Wait(() =>
{
_state = _action(_state);
});
}
public void Dispose()
{
var timer = default(System.Threading.Timer);
lock (s_timers)
{
timer = _timer;
_timer = null;
if (timer != null)
s_timers.Remove(timer);
}
if (timer != null)
{
timer.Dispose();
_gate.Dispose();
_action = Stubs<TState>.I;
}
}
}
#endif
}
}
#endif
|