ConcurrencyAbstractionLayerImpl.Windows.cs 2.9 KB

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