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 }
原文:http://www.cnblogs.com/xiangzhe-C/p/5041380.html