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.
d2964b31-b905-4b4b-a282-d36c01b58772|1|5.0
By: james
Category: C#
Tags: c#, threads, threadpool