TaskHelpers.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. #if !NO_TPL && !NO_TASK_DELAY
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Reactive.Concurrency
  8. {
  9. static class TaskHelpers
  10. {
  11. private const int MAX_DELAY = int.MaxValue;
  12. public static Task Delay(TimeSpan delay, CancellationToken token)
  13. {
  14. var milliseconds = (long)delay.TotalMilliseconds;
  15. if (milliseconds > MAX_DELAY)
  16. {
  17. var remainder = delay - TimeSpan.FromMilliseconds(MAX_DELAY);
  18. return
  19. #if USE_TASKEX
  20. TaskEx.Delay(MAX_DELAY, token)
  21. #else
  22. Task.Delay(MAX_DELAY, token)
  23. #endif
  24. .ContinueWith(_ => Delay(remainder, token), TaskContinuationOptions.ExecuteSynchronously)
  25. .Unwrap();
  26. }
  27. #if USE_TASKEX
  28. return TaskEx.Delay(delay, token);
  29. #else
  30. return Task.Delay(delay, token);
  31. #endif
  32. }
  33. }
  34. }
  35. #endif