// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Threading; namespace PoolOld { public class Program { public class Counter { public int N { get; set; } } public class Data { public string S { get; set; } } public class Processor { private Data d; public Processor(Data d) { this.d = d; } public void Run(Object c) { // simulate a lot of work that takes 0.1 second string s = d.S; Thread.Sleep(100); d.S = s + "X"; // count down lock(c) { ((Counter)c).N--; } } } public static void Test(int njobs, int nthreads) { // setup data Data[] d = new Data[njobs]; for(int i = 0; i < njobs; i++) { d[i] = new Data { S = "X" }; } // process DateTime dt1 = DateTime.Now; ThreadPool.SetMinThreads(nthreads, nthreads); ThreadPool.SetMaxThreads(nthreads, nthreads); // submit jobs Counter c = new Counter { N = njobs }; for(int i = 0; i < njobs; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback((new Processor(d[i])).Run), c); } // wait for jobs to complete while(true) { lock(c) { if(c.N <= 0) break; } Thread.Sleep(25); } DateTime dt2 = DateTime.Now; Console.WriteLine("{0} jobs executing in {1} threads : {2:F1} seconds", njobs, nthreads, (dt2 - dt1).TotalSeconds); // check data for(int i = 0; i < njobs; i++) { if(d[i].S != "XX") Console.WriteLine("Ooops"); } } public static void Main(string[] args) { Test(256, 1); Test(256, 2); Test(256, 4); Test(256, 8); Test(256, 16); Test(256, 32); Test(256, 64); Console.ReadKey(); } } }