using System; using System.Threading; using System.Collections.Generic; namespace ln.http.threads { public delegate void JobDelegate(); public class Pool { public int Timeout { get; set; } = 15000; ISet threads = new HashSet(); Queue queuedJobs = new Queue(); HashSet idleThreads = new HashSet(); public Pool() { } private void AllocateThread() { Thread thread = new Thread(pool_thread); thread.Start(); } public void Enqueue(JobDelegate job) { lock (this) { queuedJobs.Enqueue(job); if (idleThreads.Count == 0) { AllocateThread(); } else { Monitor.Pulse(this); } } } private void pool_thread() { Thread me = Thread.CurrentThread; try { JobDelegate job = null; do { lock (this) { if (queuedJobs.Count == 0) { idleThreads.Add(me); bool s = Monitor.Wait(this, Timeout); idleThreads.Remove(me); if (!s) break; } job = queuedJobs.Dequeue(); } job(); } while (true); } catch (Exception e) { Console.WriteLine("Exception in worker thread: {0}", e); } lock (this) { threads.Remove(me); } } } }