[英]Thread Pools - restricting calls to certain methods
有沒有辦法告訴線程池mananger只有x個線程調用特定方法或方法組?
我有一個應用程序,我在整個地方使用線程池工作線程,它可以游泳; 然而,我委托給工作線程的任務之一是Web服務調用,它將拒絕超過5個並發請求。 我不想將線程池限制為5個線程,因為許多其他東西使用線程並且可以處理更多。
有沒有辦法“划分”一個線程池,說“你將在任何時間點都有最多x個線程活動執行這個特定的事情,但你們其余的線程可以去做其他事情”?
使用信號量將對稀缺資源的訪問限制為最大值。 5。
可以將信號量配置為僅允許N個線程的並發訪問。 您需要在N = 5時配置信號量,並在調用Web服務之前讓所有線程等待它。
創建另一個線程池和SetMaxThreads(5) - 這是最簡單的方法。
好的,你不能用Threadpool類來做。
所以我沒有被投票:
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,但它是一個具有固定線程數的線程池
您可以使用多個線程池。 對於您的Web服務請求具有最多5個線程的線程池A,對於其他所有內容,具有更高的最大線程池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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.