Hello,
I've written a small program that spawns 10 threads from the .Net
ThreadPool (see code below).
I'm puzzled because when I run the code, I can see the 10 threads
being created in less than a second (so more or less at the same
time). Therefore I would expect them to finish at the same time too.
But instead the message 'Thread finished' is displayed every second or
so before all the threads finally exits. Why is that ?
Also, maybe I misunderstood something but I've tried setting the
maximum threads in the pool to 3 by doing ThreadPool.SetMaxThreads(3,
1) and seems to have no effects, i.e the 10 threads are spawned before
any of them complete. Why ?
class Program
{
static void Main(string[] args)
{
Start();
}
static void Start()
{
ManualResetEvent[] ev = null;
for (int i = 0; i < 10; i++)
{
Array.Resize(ref ev, i + 1);
ev[i] = new ManualResetEvent(false);
WebCrawler w = new WebCrawler(ev[i]);
ThreadPool.QueueUserWorkItem(new WaitCallback
(w.Crawl));
}
WaitHandle.WaitAll(ev);
}
internal class WebCrawler{
private ManualResetEvent _event;
public WebCrawler(ManualResetEvent pEvent)
{
_event = pEvent;
}
public void Crawl(object stateInfo)
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("Thread finished");
_event.Set();
}
}
}