Thread Pool C# with Example



Thread Pool C# with Example

 using System;
using System.Threading;

namespace CSharpMultiThreading
{
	class PrintHello
	{
		public void Display()
		{
			Console.Write("Hello!");
			
			for(int i=1; i<10; i++)
				Console.Write("  {0}", i);
			
			Console.WriteLine();
		}
	}
	
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Main thread started. ThreadID = {0}",
			Thread.CurrentThread.ManagedThreadId);
			PrintHello p = new PrintHello();
			
			WaitCallback workItem = new WaitCallback(PrintTheNumbers);
			// Queue the method ten times.
			for (int i = 0; i < 10; i++)
			{
				ThreadPool.QueueUserWorkItem(workItem, p);
			}
			Console.WriteLine("All tasks queued");
			Console.ReadLine();
		}
		
		static void PrintTheNumbers(object state)
		{
			PrintHello task = (PrintHello)state;
			task.Display();
		}
	}
} 

0 Comment's

Comment Form

Submit Comment