using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Data; namespace MSCTool { public class CheckUpdateService { public CheckUpdateService() { //设定最大的Net并发连接数 System.Net.ServicePointManager.DefaultConnectionLimit = 500; ThreadPool.SetMinThreads(15, 2);//设置最小的工作线程数和IO线程数 } private int MaxThread = 10;//最大的纠偏线程数 private static Random m_rand = new Random(Guid.NewGuid().GetHashCode());//创建随机数 private static object m_objLock = new object();//添加列表锁定 private AutoResetEvent[] InitAutoResetEvent() { //对每个线程提供一个完成信号,初始化为未终止状态 AutoResetEvent[] autoEvents = new AutoResetEvent[MaxThread]; for (int i = 0; i < MaxThread; i++) autoEvents[i] = new AutoResetEvent(false); return autoEvents; } /// <summary> /// 将处理完的信息添加至List列表 /// </summary> /// <param name="lst"></param> /// <param name="info"></param> public void AddItemToList(List<CIT3> lst, CIT3 info) { lock (m_objLock) { lst.Add(info); } } public void OnStart() { try { //在线程池中引入可执行的方法,一个循环不断判断 ThreadPool.QueueUserWorkItem(_ => { for (int k = 0; k < 3; k++) { AutoResetEvent[] autoEvents = InitAutoResetEvent(); //得到处理数据集 List<CIT3> lst = GetBeforeList(); int iCount = lst.Count; //获取要处理的数据行数 var dataIndex = -1; for (int i = 0; i < MaxThread; i++) //像线程池加入执行队列 { ThreadPool.QueueUserWorkItem(data => { int iIndex = (int)data;//线程序号0->MaxThread while (true) { Interlocked.Increment(ref dataIndex); if (dataIndex >= iCount) break; LogHelper.WriteLog(lst[dataIndex].MID.ToString(), true); } autoEvents[iIndex].Set(); }, i); } //等待收到所有的信号 ManualResetEvent.WaitAll(autoEvents); } }); } catch (Exception exc) { LogHelper.WriteLog("Error3:" + exc.StackTrace, true); } } /// <summary> /// 数据库提取预处理数据 /// </summary> /// <returns>预处理数据集</returns> public List<CIT3> GetBeforeList() { List<CIT3> list = new List<CIT3>(); for (int i = 0; i < 100; i++) { list.Add(new CIT3() { MID = i + 1 }); } return list; } } }