Max # of worker threads and Begin Invoke

  • Thread starter Thread starter Mark Hoffman
  • Start date Start date
M

Mark Hoffman

All,

From what I've read, the CLR gives each App Domain a thread pool of 25
threads, and once this pool is exhausted then any new threads created with
BeginInvoke will block until the pool frees up another thread. Am I right on
that?

I did a little test where I went into a loop and attempted to spawn 50 new
worker threads with a call to BeginInvoke that used an asynchronous
callback. I expected it to launch 24 threads, then block for a while until
the threads completed. But instead, it never blocked and completed the loop
immediately. Here is a snippet of the code:

for (int i=0;i<50;i++)
{
WorkerThread_Delegate dlgt = new
WorkerThread_Delegate(Class2.WorkerThread);
IAsyncResult ar = dlgt.BeginInvoke(new AsyncCallback(Callback),dlgt );
}
Console.WriteLine("** FINISHED SPAWNING THREADS **");

(The Class2.WorkerThread simply causes the thread to sleep for 10 seconds.)

So when I run this, it immediately finishes the loop and outputs the line
about finished spawning threads. Why didn't it block after creating the
first 24 threads? Is it because I am using an asynchronous callback?

Thanks for any info. I've read what I've seen on MSDN, but either I missed
something or it just isn't sinking in because I don't fully understand this
behavior.

Mark
 
Mark,
The way I understand it BeginInvoke, places the request in a queue and
immediately returns. The 25 worker threads check this queue for the next
item to work on and start executing that request.

So what happened is you have 25 threads doing working and 25 items waiting
in a queue someplace. As the first 25 items are finished, they (the threads)
will take items out of the queue and process those requests.

Hence your loop finishes right away.

I suspect someplace under the covers BeginInvoke simply uses
System.Threading.ThreadPool.QueueUserWorkItem or BeginInvoke &
QueueUserWorkItem both wind up calling the same thing...

Hope this helps
Jay
 
Back
Top