DispatcherHelpers.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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.Reactive.Disposables;
  5. #if NET472 || CSWINRT
  6. using System.Threading;
  7. #endif
  8. #if HAS_DISPATCHER
  9. using System;
  10. using System.Windows.Threading;
  11. #endif
  12. namespace ReactiveTests
  13. {
  14. #if HAS_DISPATCHER
  15. internal static class DispatcherHelpers
  16. {
  17. private static readonly Semaphore s_oneDispatcher = new(1, 1);
  18. public static IDisposable RunTest(out DispatcherWrapper wrapper)
  19. {
  20. s_oneDispatcher.WaitOne();
  21. #if DESKTOPCLR
  22. var dispatcher = new Thread(Dispatcher.Run);
  23. dispatcher.IsBackground = true;
  24. dispatcher.Start();
  25. while (Dispatcher.FromThread(dispatcher) == null)
  26. Thread.Sleep(10);
  27. var d = Dispatcher.FromThread(dispatcher);
  28. while (d.BeginInvoke(new Action(() => { })).Status == DispatcherOperationStatus.Aborted) ;
  29. wrapper = new DispatcherWrapper(d);
  30. return new DispatcherTest(dispatcher);
  31. #else
  32. wrapper = new DispatcherWrapper(Dispatcher.CurrentDispatcher);
  33. return Disposable.Empty; // REVIEW: Anything to shut down?
  34. #endif
  35. }
  36. #if DESKTOPCLR
  37. private sealed class DispatcherTest : IDisposable
  38. {
  39. private readonly Thread _t;
  40. public DispatcherTest(Thread t)
  41. {
  42. _t = t;
  43. }
  44. public void Dispose()
  45. {
  46. var d = Dispatcher.FromThread(_t);
  47. d.BeginInvoke(new Action(() => d.InvokeShutdown()));
  48. _t.Join();
  49. s_oneDispatcher.Release();
  50. }
  51. }
  52. #endif
  53. }
  54. internal class DispatcherWrapper
  55. {
  56. private readonly Dispatcher _dispatcher;
  57. public DispatcherWrapper(Dispatcher dispatcher)
  58. {
  59. _dispatcher = dispatcher;
  60. }
  61. public Dispatcher Dispatcher => _dispatcher;
  62. public static implicit operator Dispatcher(DispatcherWrapper wrapper)
  63. {
  64. return wrapper._dispatcher;
  65. }
  66. public event DispatcherUnhandledExceptionEventHandler UnhandledException
  67. {
  68. add { _dispatcher.UnhandledException += value; }
  69. remove { _dispatcher.UnhandledException -= value; }
  70. }
  71. public void BeginInvoke(Action action)
  72. {
  73. _dispatcher.BeginInvoke(action);
  74. }
  75. }
  76. #endif
  77. }