Generic ThreadPool in .NET

瘦欲@ 提交于 2019-12-04 07:41:37
Marc Gravell

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.

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!