在.NET通用线程池 [英] Generic ThreadPool in .NET
问题描述
下面对我来说是比较常见的任务,而且,我认为,对于许多.NET程序员:结果
我想使用.NET线程池对需要处理给定类型的调度工作线程。任务
Here's a relatively common task for me, and, I think, for many a .NET programmer:
I want to use the .NET ThreadPool for scheduling worker threads that need to process a given type of tasks.
作为一个进修,为线程池及其相关委托的排队方法的签名是:
As a refresher, the signatures for the queueing method of the ThreadPool and its associated delegate are:
public static bool QueueUserWorkItem (
WaitCallback callBack,
Object state
)
public delegate void WaitCallback (Object state)
因此,一个典型的通用工作线程类看起来是这样的:
Therefore, a typical generic worker thread class would look something like:
public class Worker<T> {
public void schedule(T i_task) {
ThreadPool.QueueUserWorkItem(execute, i_task)
}
private void execute(Object o){
T task = (T)o; //What happened to the type safety?
executeTask(task);
}
private void executeTask(T i_task){
//process i_task
}
}
注意状态的类型
参数?它的 对象
的!
Notice the type of the state
parameter? It's Object
!
有什么令人信服的理由,为什么.NET团队选择不让 QueueUserWorkItem
方法(或整个线程池
类)通用?我不能相信他们只是忽略它。
What's the compelling reason why the .NET team chose not to make the QueueUserWorkItem
method (or the whole ThreadPool
class) generic? I can't believe they just overlooked it.
下面是我想怎么看的:
//in the ThreadPool class:
public static bool QueueUserWorkItem<T> (
WaitCallback<T> callBack,
T state
)
public delegate void WaitCallback<T> (T state)
这将使工人阶级类型安全(和很多更清晰,恕我直言)
This would make the worker class type-safe (and a lot clearer, IMHO):
public class Worker<T> {
public void schedule(T i_task) {
ThreadPool.QueueUserWorkItem<T>(execute, i_task)
}
private void execute(T i_task){
//process i_task
}
}
我必须失去了一些东西。
I must be missing something.
推荐答案
这听起来像你所谈论的工作队列? (我听起来像大眼夹...)
It sounds like you are talking about a work queue? (and I sound like clippy...)
有关记录,线程池中的线程通常应该用于工作的小品。理论上,应该创建自己的线程长寿命队列。需要注意的是.NET 4.0,可以采用CCR / TPL库,所以我们会得到一些内在的工作队列自由 - 但它并不难写螺纹工作队列。而且你可以把它通用的,太;-p
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
重的问题 - 我更喜欢捕捉变量的方法来传递状态进入线程(无论是螺纹
,线程池
或 Control.Invoke
):
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
.
这篇关于在.NET通用线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!