DispatcherHelpers.cs 1.8 KB

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