TestLongRunningScheduler.cs 2.6 KB

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