CLR Thread pool – more effective way to manage threads
Limitations
-only background threads
-non identified…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadPoolExample { class Program { static void Main(string[] args) { ThreadPoolSomeExample(); } public static void ThreadPoolSomeExample() { Printer p = new Printer(); WaitCallback workItem = new WaitCallback(PrintTheNumbers); for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(workItem, p); } Console.WriteLine("All tasks queued"); Console.ReadLine(); } static void PrintTheNumbers(object state) { Printer task = (Printer)state; task.PrintNumbers(); } } public class Printer { private object threadLock = new object(); public void PrintNumbers() { lock (threadLock) { for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write("{0},", i); } Console.WriteLine(); } } } } |