• 使用多核处理器处理任务


     1  //记录开始处理的时间
     2             Stopwatch paddingTime = new Stopwatch();
     3             paddingTime.Start();
     4             JobHelper jobHelper = new JobHelper();
     5             int orderCount = jobHelper.GetJobCount();
     6             mutex=new Mutex(false,"CNBlogs.EmulationSystem");
     7             if (!mutex.WaitOne(0,false))
     8             {
     9                 Console.Out.WriteLine("Monitor already running...");
    10                 return;
    11             }
    12             //TaskList(orderCount, jobHelper);
    13             int maxProNumber = 500;
    14             using (_semaphoreLimit=new Semaphore(0,maxProNumber))
    15             {
    16                 //以指定的次数退出信号量并返回前一个计数
    17                 _semaphoreLimit.Release(maxProNumber);
    18                 var taskList = new List<Task>();
    19                 for (int i = 0; i < orderCount; i++)
    20                 {
    21                     int temp = i;
    22                     //如果SubmitJob有IO或者其他容易因为冲突而引起异常的话,这里需要加上lock
    23                     //lock (lockerObj)
    24                     //{
    25                     _semaphoreLimit.WaitOne();
    26                     taskList.Add(Task.Factory.StartNew(() =>
    27                     {
    28                         jobHelper.SubmitJob(temp);
    29                         //退出信号量并返回前一个计数
    30                         if (_semaphoreLimit != null) _semaphoreLimit.Release();
    31                     }));
    32                     //}
    33                 }
    34                 Task.WaitAll(taskList.ToArray());
    35             }
    36             paddingTime.Stop();
    37             var time = paddingTime.ElapsedMilliseconds;
    38             Console.WriteLine(string.Format("Complete: {0}, cost {1} ms",orderCount,time));
     1   public class JobHelper
     2     {
     3         public int GetJobCount()
     4         {
     5             return 100;
     6         }
     7 
     8         public bool SubmitJob(int jobId)
     9         {
    10             Thread.Sleep(1000);
    11             return true;
    12         }
    13     }
  • 相关阅读:
    Web API 依赖注入与扩展
    ASP.NET Web API 简介
    经典SQL语句大全_主外键_约束
    自学MVC看这里——全网最全ASP.NET MVC 教程汇总
    正则表达式的汉字匹配
    Sql Server 删除所有表
    细说ASP.NET Forms身份认证
    NET Web的身份认证
    C#百万数据查询超时问题
    nodejs 命令行交互
  • 原文地址:https://www.cnblogs.com/xiangzhe-C/p/5041380.html
Copyright © 2020-2023  润新知