DispatcherHelpers.cs 1.8 KB

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