如果要执行的内容很多,但允许开的最大线程数固定,比如20个。要等待所有线程执行完毕后才能继续,可以参考如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CDBDataMultiSync.Model;
using System.Threading;
using System.Threading.Tasks;
namespace CDBDataMultiSync.BLL
{
/// <summary>
/// 导入数据管理
/// </summary>
public class ImportDataManager
{
public void MultiImportMessage(List<Message> messageLists)
{
//创建线程等待委托列表
//List<WaitHandle> waitHandles = new List<WaitHandle>();
ThreadPool.SetMaxThreads(20, 20);
int waitThreadCount= 0; int MaxThreadCount= 0;
for (int i = 0; i < messageLists.Count;i++ )
{
//从线程池中获取一个线程来执行任务
ThreadPool.QueueUserWorkItem(new WaitCallback(CreateThreadDoTask), messageLists[i]);
}
//等待所有线程执行完毕
while(true)
{
ThreadPool.GetAvailableThreads(out wth,out mth);
if(waitThreadCount-MaxThreadCount==0)
{
Console.WriteLine("空闲线程数{0},最大线程数{1}", wth, mth);
Console.WriteLine("全部执行完毕");
break;
}
}
}
public void CreateThreadDoTask(object msgObject)
{
Message msg = (Message)msgObject;
ImportOneMessage(msg);
}
/// <summary>
/// 多线程导入
/// </summary>
/// <param name="messageLists"></param>
public void ImportOneMessage(Message msg)
{
Console.WriteLine("正在执行" + msg.BussinessName);
int wth = 0; int mth = 0;
ThreadPool.GetAvailableThreads(out wth, out mth);
Console.WriteLine("空闲线程数{0},最大线程数{1}", wth, mth);
Thread.Sleep(3000);
Console.WriteLine("执行完毕=====" + msg.BussinessName);
Console.WriteLine("空闲线程数{0},最大线程数{1}", wth, mth);
}
}
}