Created
July 13, 2016 08:50
-
-
Save mzabsky/5b2e3db262711f08bf6e1d739b52623a to your computer and use it in GitHub Desktop.
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
// This code is for demonstration purposes only and is mean to be as simple as possible. Don't use this in production! | |
public enum TaskPriority | |
{ | |
Low, | |
Normal, | |
High | |
} | |
public delegate void CustomThreadPoolTaskMethod(CustomThreadPool pool); | |
public class CustomThreadPoolTask | |
{ | |
public TaskPriority Priority { get; set; } | |
public CustomThreadPoolTaskMethod Method { get; set; } | |
} | |
public class CustomThreadPool | |
{ | |
// This is not a data structures lesson and .Net doesn't have a proper priority queue :) | |
private List<CustomThreadPoolTask> _tasks = new List<CustomThreadPoolTask>(); | |
public CustomThreadPool(int numberOfThreads) | |
{ | |
for (int i = 0; i < numberOfThreads; i++) | |
{ | |
Thread thread = new Thread(this.PooledThreadBody); | |
thread.Start(); | |
} | |
} | |
public void EnqueueTask(CustomThreadPoolTask task) | |
{ | |
lock (_tasks) | |
{ | |
_tasks.Add(task); | |
} | |
} | |
private void PooledThreadBody() | |
{ | |
while (true) | |
{ | |
// Grab first scheduled task of the highest priority in the "queue" | |
CustomThreadPoolTask taskToExecute; | |
lock (_tasks) | |
{ | |
// Fortunately, IEnumerable OrderBy is stable. | |
taskToExecute = this._tasks.OrderBy(p => (int)p.Priority).FirstOrDefault(); | |
// There are no scheduled tasks, currently. | |
if (taskToExecute == null) | |
{ | |
// Try again in a moment. | |
Thread.Sleep(TimeSpan.FromSeconds(0.1)); | |
continue; | |
} | |
_tasks.Remove(taskToExecute); | |
} | |
taskToExecute.Method(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment