ConcurrencyAbstractionLayerImpl.Windows.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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_THREAD && WINDOWS
  5. using System.Reactive.Disposables;
  6. using System.Threading;
  7. namespace System.Reactive.Concurrency
  8. {
  9. internal class /*Default*/ConcurrencyAbstractionLayerImpl : IConcurrencyAbstractionLayer
  10. {
  11. public IDisposable StartTimer(Action<object> action, object state, TimeSpan dueTime)
  12. {
  13. var res = global::Windows.System.Threading.ThreadPoolTimer.CreateTimer(
  14. tpt =>
  15. {
  16. action(state);
  17. },
  18. Normalize(dueTime)
  19. );
  20. return res.AsDisposable();
  21. }
  22. public IDisposable StartPeriodicTimer(Action action, TimeSpan period)
  23. {
  24. //
  25. // The WinRT thread pool is based on the Win32 thread pool and cannot handle
  26. // sub-1ms resolution. When passing a lower period, we get single-shot
  27. // timer behavior instead. See MSDN documentation for CreatePeriodicTimer
  28. // for more information.
  29. //
  30. if (period < TimeSpan.FromMilliseconds(1))
  31. throw new ArgumentOutOfRangeException(nameof(period), Strings_PlatformServices.WINRT_NO_SUB1MS_TIMERS);
  32. var res = global::Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(
  33. tpt =>
  34. {
  35. action();
  36. },
  37. period
  38. );
  39. return res.AsDisposable();
  40. }
  41. public IDisposable QueueUserWorkItem(Action<object> action, object state)
  42. {
  43. var res = global::Windows.System.Threading.ThreadPool.RunAsync(iaa =>
  44. {
  45. action(state);
  46. });
  47. return res.AsDisposable();
  48. }
  49. public void Sleep(TimeSpan timeout)
  50. {
  51. var e = new ManualResetEventSlim();
  52. global::Windows.System.Threading.ThreadPoolTimer.CreateTimer(
  53. tpt =>
  54. {
  55. e.Set();
  56. },
  57. Normalize(timeout)
  58. );
  59. e.Wait();
  60. }
  61. public IStopwatch StartStopwatch() => new StopwatchImpl();
  62. public bool SupportsLongRunning => false;
  63. public void StartThread(Action<object> action, object state)
  64. {
  65. throw new NotSupportedException();
  66. }
  67. private TimeSpan Normalize(TimeSpan dueTime) => dueTime < TimeSpan.Zero ? TimeSpan.Zero : dueTime;
  68. }
  69. }
  70. #endif