SynchronizationContextScheduler
Represents an object that schedules units of work on a provided SynchronizationContext.
using System.Reactive.Disposables;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Reactive.Concurrency
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class SynchronizationContextScheduler : LocalScheduler
{
private readonly SynchronizationContext _context;
private readonly bool _alwaysPost;
public SynchronizationContextScheduler(SynchronizationContext context)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
_alwaysPost = true;
}
public SynchronizationContextScheduler(SynchronizationContext context, bool alwaysPost)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
_alwaysPost = alwaysPost;
}
public override IDisposable Schedule<[System.Runtime.CompilerServices.Nullable(2)] TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
if (!_alwaysPost && _context == SynchronizationContext.Current)
return action(this, state);
SingleAssignmentDisposable d = new SingleAssignmentDisposable();
_context.PostWithStartComplete(delegate {
if (!d.IsDisposed)
d.Disposable = action(this, state);
});
return d;
}
public override IDisposable Schedule<[System.Runtime.CompilerServices.Nullable(2)] TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
TimeSpan dueTime2 = Scheduler.Normalize(dueTime);
if (dueTime2.Ticks == 0)
return Schedule(state, action);
return DefaultScheduler.Instance.Schedule(state, dueTime2, (IScheduler _, TState state1) => ((LocalScheduler)this).Schedule<TState>(state1, action));
}
}
}