TestLongRunningScheduler.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. 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. class TestLongRunningScheduler : IScheduler, ISchedulerLongRunning, IServiceProvider
  12. {
  13. private Action<ManualResetEvent> _setStart;
  14. private Action<ManualResetEvent> _setEnd;
  15. private 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. throw;
  60. _setException(ex);
  61. }
  62. finally
  63. {
  64. ee.Set();
  65. }
  66. });
  67. return d;
  68. }
  69. object IServiceProvider.GetService(Type serviceType)
  70. {
  71. if (serviceType == typeof(ISchedulerLongRunning))
  72. return this;
  73. return null;
  74. }
  75. }
  76. }