SynchronizationContextAsyncScheduler.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace System.Reactive.Concurrency
  7. {
  8. public sealed class SynchronizationContextAsyncScheduler : AsyncSchedulerBase
  9. {
  10. private readonly SynchronizationContext _context;
  11. public SynchronizationContextAsyncScheduler(SynchronizationContext context)
  12. {
  13. if (context == null)
  14. throw new ArgumentNullException(nameof(context));
  15. _context = context;
  16. }
  17. protected override Task Delay(TimeSpan dueTime, CancellationToken token) => Task.Delay(dueTime, token);
  18. protected override Task ScheduleAsyncCore(Func<CancellationToken, Task> action, CancellationToken token)
  19. {
  20. _context.Post(_ =>
  21. {
  22. if (!token.IsCancellationRequested)
  23. {
  24. action(token);
  25. }
  26. }, null);
  27. return Task.CompletedTask;
  28. }
  29. }
  30. }