using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JdLibrary.Com
{
public class WorkBackground
{
public delegate void BackgroundMethod(params object[] objs);
private int threadCount = 0;
private int MaxThreadCount = 0;
public WorkBackground(int maxThreadCount)
{
MaxThreadCount = maxThreadCount;
}
public void Run(BackgroundMethod backgroundMethod, params object[] objs)
{
while (threadCount >= MaxThreadCount)
{ Thread.Sleep(5); }
lock (this) { threadCount++; }
Thread thread = new Thread((object threadObj) =>
{
if (threadObj as object[] != null)
{ backgroundMethod(threadObj as object[]); }
else
{ backgroundMethod(); }
lock (this) { threadCount--; }
});
thread.IsBackground = true;
thread.Start(objs);
}
public void WaitComplete()
{
while (threadCount > 0)
{ Thread.Sleep(5); }
}
}
}
调用方式 开启50个线程去处理
var backWork = new JdLibrary.Com.WorkBackground(50);
foreach (var item in list)
{
backWork.Run(delegate
{
UpdateStation(item, cpid);//调用的方法,或者代码
});
}
backWork.WaitComplete();