Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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