线程平均分配
public static class TaskUtil { /// <summary> /// 多线程执行 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="action"></param> /// <param name="threadNum"></param> public static void Do<T>(List<T> list, Action<T> action, int threadNum) { object o = new object(); int count = list.Count(); int avg = count / threadNum; int yushu = count % threadNum; if (avg == 0) { ThreadStart ts = () => { foreach (var item in list) { action(item); } }; Thread t = new Thread(ts); t.Start(); } else { for (int i = 1; i <= avg; i++) { var tempList = list.Skip((i - 1) * avg).Take(avg).ToList(); if (yushu > 0) { tempList.AddRange(list.Skip(i * avg).Take(yushu)); } ThreadStart ts = () => { foreach (var item in tempList) { //在action中注意锁住非堆里面的内容,因为堆是以线程独享,栈是程序共享 action(item); Console.WriteLine(); } }; Thread t = new Thread(ts); t.Name = "线程" + i; t.Start(); } } } }