如何从线程池中找到 60%(或 N%)的线程可用性?这背后的逻辑是什么?
父线程使用线程池线程生成多个 url 并等待所有子线程完成。
代码如下;
父线程
public void Save()
{
List<Job> Jobs = PickJobs();
int workerThreads = 0,compThreads = 0;
ThreadPool.GetMinThreads(workerThreads, compThreads);
int requiredThreads = 15;
ThreadPool.SetMaxThreads(requiredThreads, compThreads);
WaitCallback waitCallBack = default(WaitCallback);
ManualResetEvent mEvent = default(ManualResetEvent);
foreach (Job _job in Jobs)
{
waitCallBack = new WaitCallback(CallBackFunc);
mEvent = new ManualResetEvent(false);
events.Add(mEvent);
ThreadPool.QueueUserWorkItem(waitCallBack, new UrlData(_job, mEvent, HttpContext.Current));
}
WaitHandle.WaitAll(events.ToArray(), 300000);//05 Minutes
}
子线程
private void CallBackFunc(object obj)
{
UrlData msgObj = (UrlData)obj;
WebRequest lWebRequest = WebRequest.Create(psUrl);
lWebRequest.Timeout = 60000;
WebResponse lWebResponse = lWebRequest.GetResponse;
msgObj.FinishEvent.Set();
}
用于跨线程通信的对象数据
public class UrlData
{
public Job job;
public ManualResetEvent FinishEvent;
public HttpContext HttpContextRef;
public UrlData(Job pJob, ManualResetEvent pEvent, HttpContext pContext)
{
job= pJob;
FinishEvent = pEvent;
HttpContextRef = pContext;
}
}
在上面的代码中,所需的线程被硬编码为:
int requiredThreads = 15;
ThreadPool.SetMaxThreads(requiredThreads, compThreads);
这种硬编码会导致线程池饥饿吗?如果线程池中没有可用的线程会发生什么?如何查找托管服务器的线程池中可用的线程总数?
谢谢。