C# - Basic ThreadPool Example

23. August 2011 22:07

 

The thread pool in c# is very simple to use. Though I should point out that it should only really be used to background resonable short tasks. It should not be used as an attempt to background long running tasks. Some people have tried and have failed as a result of doing these sorts of things. You should treat the thread pool as a limited resource of threads which should only ever contain a queue of short tasks.

 

If you do create long running tasks you run the risk of starving newly queued items on the thread queue. This resource starvation can be controlled by setting the min / max numbers of threads in the thread pool. Only for large applications should these ever need to be increased.

 

Here is a short example on using the thread pool.

 

 

class Program
{
	static void Main(string[] args)
	{
		ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);

		for (int i = 0; i < 5; i++)
		{
			Thread.Sleep(1000);
			Console.WriteLine("Main {0}", i);
		}

		Console.WriteLine("Main Program Finished");
		Console.ReadLine();
	}

	static void Run(object args)
	{

		for (int i = 0; i < 10; i++)
		{
			Thread.Sleep(1000);
			Console.WriteLine("Run {0}", i);
		}

	}
}

 

If you run the program output you will see that both functions appear to be running at the same time. They are actually both running at the same time on different threads. The alternative way to think of this is two programs each with their own stack and sharing the same memory space.

E-mail Kick it! DZone it! del.icio.us Permalink


Comments (1) -

2/21/2012 3:32:35 PM #

This is one of the best articles so far I have read online. Just useful information. Very well presented. Check this url too....
www.mindstick.com/.../

Its also having nice post with wonderful explanation on ThreadPool C#.
Thanks everyone!!

PiyushChandra India | Reply

Pingbacks and trackbacks (1)+

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading