TestLongRunningScheduler.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Reactive.Concurrency;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace ReactiveTests
  10. {
  11. internal class TestLongRunningScheduler : IScheduler, ISchedulerLongRunning, IServiceProvider
  12. {
  13. private readonly Action<ManualResetEvent> _setStart;
  14. private readonly Action<ManualResetEvent> _setEnd;
  15. private readonly Action<Exception> _setException;
  16. public TestLongRunningScheduler(Action<ManualResetEvent> setStart, Action<ManualResetEvent> setEnd)
  17. : this(setStart, setEnd, null)
  18. {
  19. }
  20. public TestLongRunningScheduler(Action<ManualResetEvent> setStart, Action<ManualResetEvent> setEnd, Action<Exception> setException)
  21. {
  22. _setStart = setStart;
  23. _setEnd = setEnd;
  24. _setException = setException;
  25. }
  26. public DateTimeOffset Now
  27. {
  28. get { return DateTimeOffset.Now; }
  29. }
  30. public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  31. {
  32. throw new NotImplementedException();
  33. }
  34. public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  35. {
  36. throw new NotImplementedException();
  37. }
  38. public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
  39. {
  40. throw new NotImplementedException();
  41. }
  42. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  43. {
  44. var d = new BooleanDisposable();
  45. var eb = new ManualResetEvent(false);
  46. _setStart(eb);
  47. var ee = new ManualResetEvent(false);
  48. _setEnd(ee);
  49. Task.Run(() =>
  50. {
  51. eb.Set();
  52. try
  53. {
  54. action(state, d);
  55. }
  56. catch (Exception ex)
  57. {
  58. if (_setException == null)
  59. {
  60. throw;
  61. }
  62. _setException(ex);
  63. }
  64. finally
  65. {
  66. ee.Set();
  67. }
  68. });
  69. return d;
  70. }
  71. object IServiceProvider.GetService(Type serviceType)
  72. {
  73. if (serviceType == typeof(ISchedulerLongRunning))
  74. {
  75. return this;
  76. }
  77. return null;
  78. }
  79. }
  80. }