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)
- If there is a queue (It should be), Can I get the count of the items (methods) that is waiting on queue?
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);
}
}
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.
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.