1、ThreadPool中可以非常方便添加线程,只是线程添加的速度非常慢,不知各位有没有遇到,测试代码如下:
private void TestFunction(object obj) //测试函数 用于给线程池调用
{
int a = 1;
int b = 1;
int c = 1;
Thread.Sleep(100 * 1000); //等等100秒
c = a + b;
}
private GetUseThreadPool() //获取使用的线程池数量
{
int WorkerMax = 0;
int WorkerAvailable = 0;
int WorkerUse = 0;
int IOMax = 0;
int IOAvailable = 0;
int IOUse = 0;
//lock (m_LOCK)
{
ThreadPool.GetMaxThreads(out WorkerMax, out IOMax);
ThreadPool.GetAvailableThreads(out WorkerAvailable,out IOAvailable);
}
WorkerUse = WorkerMax - WorkerAvailable;
IOUse = IOMax - IOAvailable;
lbl_WorkerMax.Text = WorkerMax.ToString();
lbl_WorkerUse.Text = WorkerUse.ToString();
lbl_WorkerAvailable.Text = WorkerAvailable.ToString();
lbl_IOMax.Text = IOMax.ToString();
lbl_IOUse.Text = IOUse.ToString();
lbl_IOAvailable.Text = IOAvailable.ToString();
lbl_UpdateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
private void TestThreadPool() //测试方法,创建1000个线程
{
int ThreadNum = 1000;
for (int i = 0; i < ThreadNum; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TestFunction),null);
}
}
*************************************
使用timer每1秒调用1次 GetUseThreadPool() 获取线程池使用数量,发现每秒增加2至4条线程,增加速度非常慢,请各位帮忙看看,谢谢
我们称之为 by design.
哈哈,知道了 还是基础不牢
执行下面两句,再调用线程池就不会有问题了
ThreadPool.SetMaxThreads(1000,1000);
ThreadPool.SetMinThreads(1000,1000);