imbageek
imbageek

Reputation: 649

Change the scheduler from TaskScheduler.FromCurrentSynchronizationContext() for unit tests

I'm running a Windows Forms application that need to update the GUI, and therefore have to use the scheduler that come from the current synchronization context. Code: TaskScheduler.FromCurrentSynchronizationContext()

When writing unit tests - this scheduler need to be switched because we want to use our own scheduler that run stuff concurrently and synchronously in a test. There are alternatives (injection, ManualResetEvent) but that's ugly and we don't want it.

It is possible to modify TaskScheduler.Default by using reflection to overwrite a private variable and that's great, but there is no obvious way of doing the same with TaskScheduler.FromCurrentSynchronizationContext().

So, how do you do this?

Upvotes: 0

Views: 134

Answers (1)

Pedro Pombeiro
Pedro Pombeiro

Reputation: 1652

One thing which might work when in a unit testing scenario, is to create a TestSynchronizationContext that inherits from SynchronizationContext, and assign it with SynchronizationContext.SetSynchronizationContext(). Your TestSynchronizationContext class would override Post method to instead redirect to the Send method, causing it to run synchronously.

You can find the sources here for reference.

Upvotes: 2

Related Questions