Reputation: 2673
I am trying to understand how ThreadPool.QueueWorkItem method works. But couldn't understand how it is working.
I create a simple example to test ThreadPool, when I run this code it loop quickly and stoped at Thread.Sleep() line. So what does ThreadPool do in here. Does it store 10000 method in an internal collection then execute them asynchronously. (according to some calculation internally thread count can be anything=> this is what I know)
2.In example WriteLine method is simple, but in my real appllication I am looping over 50000 items and call web service methods, database select/insert/update vb.. for each item in an array. Is it possible to do this type of thing like that?
class Program
{
static void Main(string[] args)
{
new Program().Looper();
}
public void Looper()
{
for (int i = 0; i < 10000; i++)
{
ThreadPool.QueueUserWorkItem(WriteLine, i);
}
Thread.Sleep(10000);
}
public void WriteLine(object str)
{
Debug.WriteLine((int)str);
}
}
Upvotes: 1
Views: 145
Reputation: 51329
1) If there is a queue (It should be), Can I get the count of the items (methods) that is waiting on queue?
Yes there is a queue, and no you cannot see it. It is an implementation detail of the ThreadPool, and you wouldn't really be able to do anything with it anyway.
2.In example WriteLine method is simple, but in my real appllication I am looping over 50000 items and call web service methods, database select/insert/update vb.. for each item in an array. Is it possible to do this type of thing like that?
Yes, and it sounds like it might be a good candidate for pooled execution because it involves a lot of waiting on external resources. That said, if you are on .NET 4.0 or higher you may want to look at TPL instead of accessing the threadpool yourself. TPL gives you features like Task nesting and continuation which you don't get with the ThreadPool. It also natively integrates with Async patterns, giving you improved async I/O parallelism.
Upvotes: 2
Reputation: 2785
When you queue an item, increment an int counter, then when the processes finishes executing (I believe you can have a function - delegate execute when an async process completes), then decrement that int counter and that should give you the number of threads waiting to execute. Thread.Sleep doesn't store anything, it simply halts any further processes from entering that async process.
Upvotes: 0