Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Task.Factory.StartNew ContinueWith Testing

$
0
0

I am writing a unit test to test a method in a WPF application. The WPF method code is as follow (this is a callback method from the EventAggregator):

private void OnEquipmentListUpdated(object eventArg)
    {
      Task.Factory.StartNew(
        arg =>
          {
            // Process data from eventArg

            return an array
          },
        receivedEquipmentListDateTime).ContinueWith(
          resultData =>
            {
              // Update CollectionViewSource to update UI
            },
          TaskScheduler.FromCurrentSynchronizationContext());
    }

The code works perfectly fine in WPF. When I wrote the unit test to test the method, I create a DispatcherSynchronizationContext with the code below:

var context = new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher);
      SynchronizationContext.SetSynchronizationContext(context);

However, when I call the method, the ContinueWith part of the codes are not executed. It will only be executed if I create a SynchronizationContext with the code below:

SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

However, if I do this, the code that updates the CollectionViewSource will throw an error because the code executing it is not the thread that created the objects. I checked the ThreadId and found that the ThreadId in the ContinueWith part is different than the ThreadId in the constructor.

How can I test the WPF method in this case? Many thanks in advance for any help.


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>