Azodious
Azodious

Reputation: 13882

BeginInvoke: Too Many Calls made


pls look at following piece of code.

for (int j = 0; j < 500000; j++)  
{  
    Console.WriteLine(j);  

    // Call BeginInvoke with last two parameters as null  

    IAsyncResult asyncRes = dlg.BeginInvoke(j, 4, ref refString, out outString, progressCallBack, null);   
}  

if the method that is being invoked asynchronously sleeps for 5 mins. then is it correct that 5 lac threads have been created?

Thanks.

Upvotes: 0

Views: 1238

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160992

That is generally not true. When you call BeginInvoke on a delegate, you are queuing up an asynchronous method execution.

The .NET Threadpool will decide when and how to execute your method based on the queue of work items that need processing and with the aim for maximum throughput, but certainly it will not run 500000 threads in parallel.

When I tried out your example with a sleep of 5 minutes and a little console message in the delegate only 8 threads were running initially, then slowly more were trickling in.

For a good explanation on the thread pool and asynchronous delegates read this article.

Upvotes: 4

Related Questions