AsyncScheduler.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.Runtime.CompilerServices;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Reactive.Concurrency
  8. {
  9. public static class AsyncScheduler
  10. {
  11. // TODO: Implement proper RendezVous semantics.
  12. public static ConfiguredTaskAwaitable RendezVous(this Task task, IAsyncScheduler scheduler)
  13. {
  14. return task.ConfigureAwait(true);
  15. }
  16. public static ConfiguredTaskAwaitable<T> RendezVous<T>(this Task<T> task, IAsyncScheduler scheduler)
  17. {
  18. return task.ConfigureAwait(true);
  19. }
  20. public static async Task Delay(this IAsyncScheduler scheduler, TimeSpan dueTime, CancellationToken token = default(CancellationToken))
  21. {
  22. if (scheduler == null)
  23. throw new ArgumentNullException(nameof(scheduler));
  24. var tcs = new TaskCompletionSource<bool>();
  25. var task = await scheduler.ScheduleAsync(ct =>
  26. {
  27. if (ct.IsCancellationRequested)
  28. {
  29. tcs.SetCanceled();
  30. }
  31. else
  32. {
  33. tcs.SetResult(true);
  34. }
  35. return Task.CompletedTask;
  36. }, dueTime);
  37. using (token.Register(() => task.DisposeAsync()))
  38. {
  39. await tcs.Task;
  40. }
  41. }
  42. }
  43. }