DispatcherHelpers.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 NETCOREAPP2_1 || NET46 || NETCOREAPP3_1 || CSWINRT
  5. using System.Threading;
  6. #endif
  7. #if HAS_DISPATCHER
  8. using System;
  9. using System.Windows.Threading;
  10. #endif
  11. namespace ReactiveTests
  12. {
  13. #if HAS_DISPATCHER
  14. static class DispatcherHelpers
  15. {
  16. public static DispatcherWrapper EnsureDispatcher()
  17. {
  18. #if DESKTOPCLR
  19. var dispatcher = new Thread(Dispatcher.Run);
  20. dispatcher.IsBackground = true;
  21. dispatcher.Start();
  22. while (Dispatcher.FromThread(dispatcher) == null)
  23. Thread.Sleep(10);
  24. var d = Dispatcher.FromThread(dispatcher);
  25. while (d.BeginInvoke(new Action(() => { })).Status == DispatcherOperationStatus.Aborted) ;
  26. return new DispatcherWrapper(d);
  27. #else
  28. return new DispatcherWrapper(Dispatcher.CurrentDispatcher);
  29. #endif
  30. }
  31. }
  32. class DispatcherWrapper
  33. {
  34. private Dispatcher _dispatcher;
  35. public DispatcherWrapper(Dispatcher dispatcher)
  36. {
  37. _dispatcher = dispatcher;
  38. }
  39. public Dispatcher Dispatcher { get { return _dispatcher; } }
  40. public void InvokeShutdown()
  41. {
  42. #if !USE_SL_DISPATCHER
  43. _dispatcher.InvokeShutdown();
  44. #endif
  45. }
  46. public static implicit operator Dispatcher(DispatcherWrapper wrapper)
  47. {
  48. return wrapper._dispatcher;
  49. }
  50. #if !USE_SL_DISPATCHER
  51. public event DispatcherUnhandledExceptionEventHandler UnhandledException
  52. {
  53. add { _dispatcher.UnhandledException += value; }
  54. remove { _dispatcher.UnhandledException -= value; }
  55. }
  56. #endif
  57. public void BeginInvoke(Action action)
  58. {
  59. _dispatcher.BeginInvoke(action);
  60. }
  61. }
  62. #endif
  63. }