Using the WPF Dispatcher in unit tests

前端 未结 16 2135
北恋
北恋 2020-11-27 02:48

I\'m having trouble getting the Dispatcher to run a delegate I\'m passing to it when unit testing. Everything works fine when I\'m running the program, but, during a unit te

16条回答
  •  一生所求
    2020-11-27 03:03

    I'm late but this is how I do it:

    public static void RunMessageLoop(Func action)
    {
      var originalContext = SynchronizationContext.Current;
      Exception exception = null;
      try
      {
        SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
    
        action.Invoke().ContinueWith(t =>
        {
          exception = t.Exception;
        }, TaskContinuationOptions.OnlyOnFaulted).ContinueWith(t => Dispatcher.ExitAllFrames(),
          TaskScheduler.FromCurrentSynchronizationContext());
    
        Dispatcher.Run();
      }
      finally
      {
        SynchronizationContext.SetSynchronizationContext(originalContext);
      }
      if (exception != null) throw exception;
    }
    

提交回复
热议问题