线程池 - 限制对某些方法的调用
本文关键字:方法 调用 线程 | 更新日期: 2023-09-27 18:31:37
有没有办法告诉线程池管理器只有x个线程调用特定方法或方法组?
我有一个应用程序,我到处使用线程池工作线程,它工作得很好;但是,我委托给工作线程的任务之一是 Web 服务调用,它将拒绝超过 5 个并发请求。 我不想将线程池限制为 5 个线程,因为许多其他东西都使用这些线程并且可以处理更多线程。
有没有办法"划分"线程池,说"在任何时间点,您最多将有 x 个线程在做这个特定的事情,但其余的线程可以做其他事情"?
使用信号量将对稀缺资源的访问限制为最多 5 个。
可以将信号量配置为仅允许 N 个线程的并发访问。您需要将信号量配置为 N=5,并在调用 Web 服务之前让所有线程等待它。
创建另一个线程池和 SetMaxThreads(5) - 这是最简单的方法。
好的,你不能用线程池类来做到这一点。
只是为了不让我被否决:
public abstract class Task {
public EventHandler FonComplete;
public ThreadPool myPool;
protected int param;
public Exception error;
public Task(int inParam, EventHandler OnDone) { param = inParam; FonComplete = OnDone; }
public abstract void run();
};
public class PoolThread{
private
BlockingCollection<Task> FinQueue;
public
PoolThread(BlockingCollection<Task> inQueue)
{
FinQueue=inQueue;
}
Task inMess;
public void run(){
while(true){
inMess=FinQueue.Take();
if(inMess==null) return;
try
{
inMess.run();
inMess.error = null;
}
catch (Exception e)
{
inMess.error = e;
}
inMess.FonComplete(inMess, null);
}
}
};
public class ThreadPool {
int FthreadCount;
BlockingCollection<Task> queue;
void startThread(){
PoolThread thisPoolThread=new PoolThread(queue);
Thread thisThread=new Thread(new ThreadStart(thisPoolThread.run));
thisThread.Priority = ThreadPriority.BelowNormal;
thisThread.IsBackground = true;
thisThread.Start();
}
void SetThreadCount(int newCount){
while(FthreadCount<newCount){startThread();};
while(FthreadCount>newCount){
queue.Add(default(Task));
FthreadCount--;
};
}
public ThreadPool(int initThreads){
queue=new BlockingCollection<Task>();
for(FthreadCount=0;FthreadCount<initThreads;FthreadCount++) startThread();
}
public int threadCount{
get{return FthreadCount;}
set
{
while (FthreadCount < value) {
startThread();
FthreadCount++;
};
while (FthreadCount > value)
{
queue.Add(default(Task));
FthreadCount--;
}
}
}
public void submit(Task task){
task.myPool=this;
queue.Add(task);
}
};
}
它不像"真正的"System.Threading.Threadpool,但它是一个具有固定线程数的线程池。
您可以使用多个线程池。 线程池 A 最多有 5 个线程,用于请求 Web 服务,线程池 B 的线程池 B 的最大值要高得多,用于其他所有内容。
首先,使用 Task
类,而不是直接使用 ThreadPool
。启动一个父任务,该父任务循环遍历每个工作项并启动一个子任务。父任务将使用信号量来限制并发子任务的数量。
这比让子任务在信号灯上等待要好得多,因为现在我们只有一个池线程在信号量上等待,而不是很多。
var parent = Task.Factory.StartNew(
() =>
{
var semaphore = new SemaphoreSlim(5, 5);
foreach (var workitem in YourWorkItems)
{
var capture = workitem;
semaphore.Wait();
Task.Factory.StartNew(
() =>
{
try
{
CallWebService(capture);
}
finally
{
semaphore.Release();
}
}, TaskCreationOptions.AttachedToParent);
}
}, TaskCreationOptions.LongRunning);
// Optionally wait for the parent to complete here.
// Because our child tasks are attached this will wait until everything is done.
parent.Wait();