using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; class Program { public static IEnumerable<Color> Pixels(int from, int to) { var bm = new Bitmap(@"s:\sample001.png"); for (int y = from; y < to; y++) { for (int x = 0; x < bm.Width; x++) { yield return bm.GetPixel(x, y); } } } private static bool isBlack(Color c) { return c.B == 0 && c.G == 0 && c.R == 0; } private static void count(int fromInclusive, int toExclusive, ref int count, object lockTarget) { var q = from n in Pixels(fromInclusive, toExclusive) where isBlack(n) select n; int r = q.Count(); lock (lockTarget) { count += r; } } static void Main(string[] args) { Object thisLock = new Object(); DateTime start1 = DateTime.Now; int count1 = 0; count(0, 1024, ref count1, thisLock); Console.WriteLine(DateTime.Now - start1); Console.WriteLine("{0} Black Pixels by single task", count1); DateTime start2 = DateTime.Now; int count2 = 0; Parallel.Invoke(() => count(0, 512, ref count2, thisLock), () =>count(512, 1024, ref count2, thisLock)); Console.WriteLine(DateTime.Now - start2); Console.WriteLine("{0} Black Pixels by 2 task", count2); DateTime start3 = DateTime.Now; int count3 = 0; Parallel.Invoke(() =>count(0, 342, ref count3, thisLock), () => count(342, 682, ref count3, thisLock), () => count(682, 1024, ref count3, thisLock)); Console.WriteLine(DateTime.Now - start3); Console.WriteLine("{0} Black Pixels by 3 task", count3); DateTime start4 = DateTime.Now; int count4 = 0; Parallel.Invoke(() =>count(0, 256, ref count4, thisLock), () => count(256, 512, ref count4, thisLock), () => count(512, 768, ref count4, thisLock), () => count(768, 1024, ref count4, thisLock)); Console.WriteLine(DateTime.Now - start4); Console.WriteLine("{0} Black Pixels by 4 task", count4); } } |