Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save renestein/2adea79a03ae95773635 to your computer and use it in GitHub Desktop.
Save renestein/2adea79a03ae95773635 to your computer and use it in GitHub Desktop.
[TestMethod]
public async Task Run_When_Called_From_Multiple_Threads_Then_All_Tasks_Executed()
{
const int NUMBER_OF_SCHEDULED_TASKS = 100;
const int DEFAULT_TASK_SLEEP = 100;
const int NUMBER_OF_WORKER_THREAD = 3;
var countDownEvent = new CountdownEvent(NUMBER_OF_WORKER_THREAD);
int executedTasks = 0;
var allTasks = Enumerable.Range(0, NUMBER_OF_SCHEDULED_TASKS).Select(_ => m_scheduler.Post(() => Thread.Sleep(DEFAULT_TASK_SLEEP))).ToArray();
Enumerable.Range(0, NUMBER_OF_WORKER_THREAD).Select(_ => ThreadPool.QueueUserWorkItem(__ =>
{
int tasksExecutedInThisThread = m_scheduler.Run();
Interlocked.Add(ref executedTasks, tasksExecutedInThisThread);
countDownEvent.Signal();
})).ToArray();
await Task.WhenAll(allTasks);
countDownEvent.Wait();
Assert.AreEqual(NUMBER_OF_SCHEDULED_TASKS, executedTasks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment