SynchronizationContextAsyncScheduler.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. _context = context ?? throw new ArgumentNullException(nameof(context));
  14. }
  15. protected override ValueTask Delay(TimeSpan dueTime, CancellationToken token) => new(Task.Delay(dueTime, token));
  16. protected override ValueTask ScheduleAsyncCore(Func<CancellationToken, ValueTask> action, CancellationToken token)
  17. {
  18. _context.Post(_ =>
  19. {
  20. if (!token.IsCancellationRequested)
  21. {
  22. action(token);
  23. }
  24. }, null);
  25. return default;
  26. }
  27. }
  28. }