Generic ThreadPool in .NET Generic ThreadPool in .NET multithreading multithreading

Generic ThreadPool in .NET


Since it's trivial to package whatever state you like by passing an anonymous delegate or lambda to the threadpool (through variable capture), there's no need for a generic version.

For example, you could write a utility function:

static void QueueItem<T>(Action<T> action, T state){    ThreadPool.QueueUserWorkItem(delegate { action(state); });}

But it wouldn't be terribly useful, as you can simply use a delegate yourself any time you need state in the pooled task.


It sounds like you are talking about a work queue? (and I sound like clippy...)

For the record, thread-pool threads should typically be used for short pieces of work. You should ideally create your own threads for a long-lived queue. Note that .NET 4.0 may be adopting the CCR/TPL libraries, so we'll get some inbuilt work queues for free - but it isn't hard to write a threaded work-queue. And you can make it generic, too ;-p

Re the question - I prefer the captured variables approach to passing state into threads (be they Thread, ThreadPool, or Control.Invoke):

    Thread t = new Thread(() => SomeMethod(arg));    t.IsBackground = true;    t.Name = "Worker n";    t.Start();

This gives you much more granular control over the thread, without saturating the ThreadPool.


ThreadPool exists since .NET 1.1 which didn't have Generics.

I like how they chose not to break backwards compatibility :-)