DispatcherHelpers.cs 2.3 KB

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