DispatcherBuild.cs 948 B

123456789101112131415161718192021222324252627282930
  1. using System.Threading;
  2. using System.Windows.Threading;
  3. namespace GeekDesk.MyThread
  4. {
  5. public class DispatcherBuild
  6. {
  7. //创建一个Dispatcher来单独使用ui线程
  8. public static Dispatcher Build()
  9. {
  10. Dispatcher dispatcher = null;
  11. var manualResetEvent = new ManualResetEvent(false);
  12. var thread = new System.Threading.Thread(() =>
  13. {
  14. dispatcher = Dispatcher.CurrentDispatcher;
  15. var synchronizationContext = new DispatcherSynchronizationContext(dispatcher);
  16. SynchronizationContext.SetSynchronizationContext(synchronizationContext);
  17. manualResetEvent.Set();
  18. Dispatcher.Run();
  19. });
  20. thread.IsBackground = true;
  21. thread.Start();
  22. manualResetEvent.WaitOne();
  23. manualResetEvent.Dispose();
  24. return dispatcher;
  25. }
  26. }
  27. }