DispatcherHelpers.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 || NET472 || 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. _dispatcher.InvokeShutdown();
  43. }
  44. public static implicit operator Dispatcher(DispatcherWrapper wrapper)
  45. {
  46. return wrapper._dispatcher;
  47. }
  48. public event DispatcherUnhandledExceptionEventHandler UnhandledException
  49. {
  50. add { _dispatcher.UnhandledException += value; }
  51. remove { _dispatcher.UnhandledException -= value; }
  52. }
  53. public void BeginInvoke(Action action)
  54. {
  55. _dispatcher.BeginInvoke(action);
  56. }
  57. }
  58. #endif
  59. }