Skip to content

Instantly share code, notes, and snippets.

@mzabsky
Created July 13, 2016 08:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzabsky/5b2e3db262711f08bf6e1d739b52623a to your computer and use it in GitHub Desktop.
Save mzabsky/5b2e3db262711f08bf6e1d739b52623a to your computer and use it in GitHub Desktop.
// 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