// 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.Collections.Generic; using System.Linq; using System.Threading; namespace Adv { public class Program { public class Data { public string S { get; set; } } public class Processor { private Data d; public Processor(Data d) { this.d = d; } public void Run() { // simulate a lot of work that takes 0.1 second string s = d.S; Thread.Sleep(100); d.S = s + "X"; } } public static void Test(bool par, int njobs) { // 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; if(par) { d.AsParallel().ForAll(o => (new Processor(o)).Run()); } else { d.ToList().ForEach(o => (new Processor(o)).Run()); } DateTime dt2 = DateTime.Now; Console.WriteLine("{0} jobs executing in {1} threads : {2:F1} seconds", njobs, par ? "many" : "one", (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(false, 256); Test(true, 256); Console.ReadKey(); } } }