Skip to content

Instantly share code, notes, and snippets.

@codereflection
Created December 20, 2013 20:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codereflection/8060574 to your computer and use it in GitHub Desktop.
Save codereflection/8060574 to your computer and use it in GitHub Desktop.
Getting unit tests to run under a single thread. Just inherit the WithASingleThreadRestriction class from your unit tests and they'll run under a single thread making unit testing much easier.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Tests
{
public class CurrentThreadTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task)
{
TryExecuteTask(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return TryExecuteTask(task);
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return Enumerable.Empty<Task>();
}
/// <summary>
/// Replaces the current task scheduler with an instance of the CurrentThreadTaskScheduler
/// using reflection.
/// </summary>
public void Start()
{
var taskSchedulerType = typeof (TaskScheduler);
var defaultTaskSchedulerField = taskSchedulerType.GetField("s_defaultTaskScheduler", BindingFlags.SetField | BindingFlags.Static | BindingFlags.NonPublic);
if (defaultTaskSchedulerField != null) defaultTaskSchedulerField.SetValue(null, this);
}
}
}
namespace Tests
{
public class WithASingleThreadRestriction
{
public WithASingleThreadRestriction()
{
var currentThreadTaskScheduler = new CurrentThreadTaskScheduler();
currentThreadTaskScheduler.Start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment