ConcurrencyAbstractionLayerImpl.Windows.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if NO_THREAD && WINDOWS
  3. using System;
  4. using System.Collections.Generic;
  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 Disposable.Create(res.Cancel);
  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("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 Disposable.Create(res.Cancel);
  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 Disposable.Create(res.Cancel);
  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()
  62. {
  63. #if !NO_STOPWATCH
  64. return new StopwatchImpl();
  65. #else
  66. return new DefaultStopwatch();
  67. #endif
  68. }
  69. public bool SupportsLongRunning
  70. {
  71. get { return false; }
  72. }
  73. public void StartThread(Action<object> action, object state)
  74. {
  75. throw new NotSupportedException();
  76. }
  77. private TimeSpan Normalize(TimeSpan dueTime)
  78. {
  79. if (dueTime < TimeSpan.Zero)
  80. return TimeSpan.Zero;
  81. return dueTime;
  82. }
  83. }
  84. }
  85. #endif