// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace E { public class Program { public static IEnumerable Lookup() { using(SqlConnection con = new SqlConnection(@"Server=ARNEPC4\SQLEXPRESS;Database=Test;Integrated Security=SSPI")) { con.Open(); SqlCommand cmd = new SqlCommand("SELECT f1 FROM T1", con); SqlDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) { yield return (int)rdr[0]; } rdr.Close(); } } public static void TestSingleThreaded() { DateTime t1 = DateTime.Now; foreach(int v in Lookup()) { Console.WriteLine(v); Thread.Sleep(1000); } DateTime t2 = DateTime.Now; Console.WriteLine((t2 - t1).TotalSeconds); } public static void TestMultiThreadedUnsafe() { DateTime t1 = DateTime.Now; Parallel.ForEach(Lookup(), v => { Console.WriteLine(v); Thread.Sleep(1000); }); DateTime t2 = DateTime.Now; Console.WriteLine((t2 - t1).TotalSeconds); } public static void TestMultiThreadedSafe() { DateTime t1 = DateTime.Now; Parallel.ForEach(Lookup().ToList(), v => { Console.WriteLine(v); Thread.Sleep(1000); }); DateTime t2 = DateTime.Now; Console.WriteLine((t2 - t1).TotalSeconds); } public static void Main(string[] args) { TestSingleThreaded(); TestMultiThreadedUnsafe(); TestMultiThreadedSafe(); } } }