Skip to content

Instantly share code, notes, and snippets.

Created December 29, 2013 16:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8172108 to your computer and use it in GitHub Desktop.
Save anonymous/8172108 to your computer and use it in GitHub Desktop.
Deterministic task scheduler that allows unit testing the functionality of your .NET code which spawns new threads via tasks. The DeterministicTaskScheduler can replace the default TaskScheduler of the .NET Framework Class Library during unit tests.
/// <summary>
/// TaskScheduker for executing tasks on the same thread that calls RunTasksUntilIdle() or RunPendingTasks()
/// </summary>
public class DeterministicTaskScheduler : TaskScheduler
{
private List<Task> scheduledTasks = new List<Task>();
#region TaskScheduler methods
protected override void QueueTask(Task task)
{
scheduledTasks.Add(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
scheduledTasks.Add(task);
return false;
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return scheduledTasks;
}
public override int MaximumConcurrencyLevel { get { return 1; } }
#endregion
/// <summary>
/// Executes the scheduled Tasks synchronously on the current thread. If those tasks schedule new tasks
/// they will also be executed until no pending tasks are left.
/// </summary>
public void RunTasksUntilIdle()
{
while (scheduledTasks.Any())
{
this.RunPendingTasks();
}
}
/// <summary>
/// Executes the scheduled Tasks synchronously on the current thread. If those tasks schedule new tasks
/// they will only be executed with the next call to RunTasksUntilIdle() or RunPendingTasks().
/// </summary>
public void RunPendingTasks()
{
foreach (var task in scheduledTasks.ToArray())
{
this.TryExecuteTask(task);
scheduledTasks.Remove(task);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment