DispatcherHelpers.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. #if NETCOREAPP1_1 || NET46 || NETCOREAPP1_0
  5. using System.Threading;
  6. #endif
  7. #if HAS_DISPATCHER
  8. using System.Windows.Threading;
  9. #endif
  10. namespace ReactiveTests
  11. {
  12. #if HAS_DISPATCHER
  13. static class DispatcherHelpers
  14. {
  15. public static DispatcherWrapper EnsureDispatcher()
  16. {
  17. #if DESKTOPCLR
  18. var dispatcher = new Thread(Dispatcher.Run);
  19. dispatcher.IsBackground = true;
  20. dispatcher.Start();
  21. while (Dispatcher.FromThread(dispatcher) == null)
  22. Thread.Sleep(10);
  23. var d = Dispatcher.FromThread(dispatcher);
  24. while (d.BeginInvoke(new Action(() => { })).Status == DispatcherOperationStatus.Aborted) ;
  25. return new DispatcherWrapper(d);
  26. #else
  27. return new DispatcherWrapper(Dispatcher.CurrentDispatcher);
  28. #endif
  29. }
  30. }
  31. class DispatcherWrapper
  32. {
  33. private Dispatcher _dispatcher;
  34. public DispatcherWrapper(Dispatcher dispatcher)
  35. {
  36. _dispatcher = dispatcher;
  37. }
  38. public Dispatcher Dispatcher { get { return _dispatcher; } }
  39. public void InvokeShutdown()
  40. {
  41. #if !USE_SL_DISPATCHER
  42. _dispatcher.InvokeShutdown();
  43. #endif
  44. }
  45. public static implicit operator Dispatcher(DispatcherWrapper wrapper)
  46. {
  47. return wrapper._dispatcher;
  48. }
  49. #if !USE_SL_DISPATCHER
  50. public event DispatcherUnhandledExceptionEventHandler UnhandledException
  51. {
  52. add { _dispatcher.UnhandledException += value; }
  53. remove { _dispatcher.UnhandledException -= value; }
  54. }
  55. #endif
  56. public void BeginInvoke(Action action)
  57. {
  58. _dispatcher.BeginInvoke(action);
  59. }
  60. }
  61. #endif
  62. }