多线程

/// <summary>
/// 多线程调用WCF
/// </summary>
/// <param name="select">调用WCF的方式,1=Restful,2=Tcp</param>
/// <param name="num"></param>
static void DoTest_MultiThread(string select, long num)
{
  int n_max_thread = 10; // 设置并行最大为10个线程
  int n_total_thread = 0; // 用来控制:主程序的结束执行,当所有任务线程执行完毕
  
  ILog log_add = new LogHelper("Add_Thread");
  ILog log_del = new LogHelper("Del_Thread");
  ILog log_wait = new LogHelper("Wait_Thread");
  ILog log_set = new LogHelper("Set_Thread");
  ILog log_for = new LogHelper("For_Thread");
  
  Console.Title = string.Format("调用WCF的方式 => {0}, 调用次数=> {1}"
    , select == "1" ? "Restful" : "Socket"
    , num);
    
  List<int> list_Thread = new List<int>();
  
  System.Threading.AutoResetEvent wait_sync = new System.Threading.AutoResetEvent(false); // 用来控制:并发最大个数线程=n_max_thread
  System.Threading.AutoResetEvent wait_main = new System.Threading.AutoResetEvent(false); // 用来控制:主程序的结束执行,当所有任务线程执行完毕
  
  DateTime date_step = DateTime.Now;
  for (long i = 0; i < num; i++)
  {
    Num_Query_Static++;
    if (i >0 && (i+1-1) % n_max_thread == 0) // -1 表示第max个线程尚未开始
    {
      //log_wait.Info(string.Format("thread n= {0},for i= {1}", dic_Thread.Count, i + 1));
      wait_sync.WaitOne(); // 每次并发10个线程,等待处理完毕后,在发送下一次并发线程
    }
    log_for.Info(string.Format("thread n= {0},for i= {1}", list_Thread.Count, i + 1));
  
    System.Threading.ThreadPool.QueueUserWorkItem
      ((data) =>
      {
        int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
        System.Threading.Monitor.Enter(list_Thread);
        list_Thread.Add(id);
        System.Threading.Monitor.Exit(list_Thread);
  
        log_add.Info(string.Format("id={0}, count={1}", id, list_Thread.Count)); // 日志
  
        if (select == "1") // Restful方式调用
        {
          Query_Htty();
        }
        else
        {
          Query_Socket();
        }
  
        n_total_thread += 1;
        if (list_Thread.Count == (n_max_thread) || n_total_thread == num)
        {
          list_Thread.Clear();
          //log_set.Info(string.Format("thread n= {0},for i= {1}", dic_Thread.Count, i + 1));
          //wait_sync.Set(); 
          if (n_total_thread != num)
          {
            wait_sync.Set(); // 任务线程,继续执行
          }
          else
          {
            wait_main.Set(); // 主程序线程,继续执行
          }
        }
      }, list_Thread);
  }
  
  wait_main.WaitOne();
  
  Console.WriteLine(string.Format("总测试{0}次,总耗时{1}, 平均耗时{2}"
    , num
    , (DateTime.Now - date_step).ToString()
    , (DateTime.Now - date_step).TotalMilliseconds / num));
  
  Query_Thread();
}

 

posted @ 2019-07-09 16:05  蓝雨冰城  阅读(107)  评论(0编辑  收藏  举报