DispatcherHelpers.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System;
  3. #if NETCOREAPP1_0
  4. using System.Threading;
  5. #elif !WINDOWS_UWP
  6. using System.Windows.Threading;
  7. #endif
  8. namespace ReactiveTests
  9. {
  10. #if HAS_DISPATCHER
  11. static class DispatcherHelpers
  12. {
  13. public static DispatcherWrapper EnsureDispatcher()
  14. {
  15. #if DESKTOPCLR
  16. var dispatcher = new Thread(Dispatcher.Run);
  17. dispatcher.IsBackground = true;
  18. dispatcher.Start();
  19. while (Dispatcher.FromThread(dispatcher) == null)
  20. Thread.Sleep(10);
  21. var d = Dispatcher.FromThread(dispatcher);
  22. while (d.BeginInvoke(new Action(() => { })).Status == DispatcherOperationStatus.Aborted) ;
  23. return new DispatcherWrapper(d);
  24. #else
  25. return new DispatcherWrapper(Dispatcher.CurrentDispatcher);
  26. #endif
  27. }
  28. }
  29. class DispatcherWrapper
  30. {
  31. private Dispatcher _dispatcher;
  32. public DispatcherWrapper(Dispatcher dispatcher)
  33. {
  34. _dispatcher = dispatcher;
  35. }
  36. public Dispatcher Dispatcher { get { return _dispatcher; } }
  37. public void InvokeShutdown()
  38. {
  39. #if !USE_SL_DISPATCHER
  40. _dispatcher.InvokeShutdown();
  41. #endif
  42. }
  43. public static implicit operator Dispatcher(DispatcherWrapper wrapper)
  44. {
  45. return wrapper._dispatcher;
  46. }
  47. #if !USE_SL_DISPATCHER
  48. public event DispatcherUnhandledExceptionEventHandler UnhandledException
  49. {
  50. add { _dispatcher.UnhandledException += value; }
  51. remove { _dispatcher.UnhandledException -= value; }
  52. }
  53. #endif
  54. public void BeginInvoke(Action action)
  55. {
  56. _dispatcher.BeginInvoke(action);
  57. }
  58. }
  59. #endif
  60. }