mercredi 7 octobre 2015

Await vs Synchronous SynchronizationContext

Was considering using CurrentThreadTaskScheduler to provide a synchronous SynchronizationContext to assist with integration testing my async code that calls out to a web service. In some cases my tests were failing because results were returning after the test had already finished.

Figured for testing purposes, I could use CurrentThreadTaskScheduler to force the logic to flow synchronously in a controlled manner. However, It seems like I can acheive this without CurrentThreadTaskScheduler, simply by using await. So question is, what is the difference between these two passing tests that mimic how the webservice is called?

// THIS IS HOW THE WEBSERVICE IS CALLED NOW USING TASK RUN
int a = 1;
await Task.Run(() => 
{
    Task.Delay(2000);
    a = 2;
});
Assert.AreEqual(2, a);

and

// THIS IS WHAT I AM CONSIDERING TO USE INSTEAD
var scheduler = new CurrentThreadTaskScheduler();
int a = 1;
await new TaskFactory(scheduler).StartNew(
    () =>
    {
        Task.Delay(2000);
        a = 2;
    });

Assert.AreEqual(2, a);

For reference, CurrentThreadTaskScheduler class

public class CurrentThreadTaskScheduler : TaskScheduler
{

protected override void QueueTask(Task task)
{
    this.TryExecuteTask(task);
}

protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
    return this.TryExecuteTask(task);
}

protected override IEnumerable<Task> GetScheduledTasks()
{
    return Enumerable.Empty<Task>();
}

public override int MaximumConcurrencyLevel
{
    get
    {
        return 1;
    }
}
}

Aucun commentaire:

Enregistrer un commentaire