mercredi 6 mai 2015

Testing thread sensitive execution of tasks

I have a function that is supposed to initiate a task composed of three executions chained together, with the first delegate executing on a worker thread with the subsequent two delegates executed on the main thread. It looks something like this:

public void RunAsync(Action workerFunction, Action mainFunction1, Action mainFunction2)
{
   Task.Factory.StartNew(workerFunction)
      .ContinueWith(mainFunction1, TaskScheduler.FromCurrentSynchronizationContext())
      .ContinueWith(mainFunction2, TaskScheduler.FromCurrentSynchronizationContext());
}

This code works fine in production, but I would like to be able to verify that delegates are being executed on the correct thread in test. Unfortunatly, it seems like the tasks are not being synchronized in the same manner as when executed in the main application. Ideally I would be able to do something like this:

[TestMethod]
public void TestRunAsync()
{
    var mainthreadId = Thread.ManagedThreadId;
    var mainFunction1Thread = 0;
    var mainFunction2Thread = 0;

    Action mainFunction1 = x => mainFunction1Thread = Thread.ManagedThreadId;
    Action mainFunction2 = x => mainFunction2Thread = Thread.ManagedThreadId;

    RunAsync(x => {}, mainFunction1, mainFunction2);

    // wait for runAsync to finish

    Assert.AreEqual(mainThreadId, mainFunction1Thread);
    Assert.AreEqual(mainThreadId, mainFunction2Thread);
}

Trying this out shows me that the different delegates are actually being run on completely different threads, despite the SynchronizationContext being set.

Is there a better way to test this behavior in test?

Aucun commentaire:

Enregistrer un commentaire