• 主线程等待子线程执行二


    如果要执行的内容很多,但允许开的最大线程数固定,比如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);
            }

        }
    }

  • 相关阅读:
    家居有线网络布线方案(转)
    ARP、Tracert、Route 与 NBTStat 命令详解(转)
    集线器、路由器、交换机、第三层交换技术(转)
    C#版nbtstat
    交换机常见故障的一般分类和排障步骤(转)
    Women guojia keneng zai 2015 nian qianhou wancheng di yi ci xiandaihua(拼音化汉字)
    IPv6协议在各操作系统下的安装与配置(转)
    具有字典验证的记事本
    子网掩码计算方法(转)
    最后推荐一篇关于PreEcho的总结论文
  • 原文地址:https://www.cnblogs.com/iampkm/p/2707063.html
Copyright © 2020-2023  润新知