Created
December 29, 2013 16:36
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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