using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class CSpiderCtrl
{
//将线程池对象作为一个全局便来给你
static Semaphore semaphore;
public static void Run()
{
//创建SuperLCBB客户端对象
var oClient = new ServiceReference_SuperLCBB.SOAServiceClient();
//初始化的时候new最大的线程池个数255(这个数值根据实际情况来判断,如果服务器上面的东西很少,则可以设置大点)
semaphore = new Semaphore(250,255);
CLogService.Instance.Debug("又一轮定时采集");
_TestBedGo(oClient);
}
//执行多线程的方法
private static void _TestBedGo(ServiceReference_SuperLCBB.SOAServiceClient oClient)
{
List<string> lstExceptPDUs = new List<string>() { "SUPERLABEXP" };
var oTestBedRes = oClient.GetTestBedExceptSomePDU(lstExceptPDUs,true);
if (CKVRes.ERRCODE_SUCCESS != oTestBedRes.ErrCode)
{
ClogService.Instance.Error("xxx");
return;
}
var lstTestBed = oTestBedRes.ToDocumentsEx();
System.Threading.Tasks.Parallel.ForEach(lstTestBed,(oTestBedRes)=>
{
//一次最多255个线程,超过255的必须等待线程池释放一个线程出来才能
semaphore.WaitOne();
//ClogService.Instance.Inof("开始采集测试床"+oTestBed(TBLTestBed.PROP_NAME));
//Thread.Sleep(2000);
var strTestBedName = oTestBedRes(TBLTestBed.PROP_NAME) as string;
var strSuperDevIP = oTestBedRes(IBLTestBed.PROP_SIPERDEVIP) as string;
var strTestBedGID = oTestBedRes(TBLTestBed.PROP_GID) as string;
var strPdu = oTestBedRes(TBLTestBed.PROP_PDUGID) as string;
Thread.Sleep(new Random().Next(1000,5000));
var oGetRootDeviceByTestBedGIDRes = oClient.GetRootDeviceByTestBedGID(strTestBedGID);
CLogService.Instance.Debug(strPdu+"一测试床Name"+strTestBedName + "开始");
Stopwatch sp = new Stopwatch();
sp.Start();
if (oGetRootDeviceByTestBedGIDRes.ErrorCode != CKVRes.ERRORCODE_SUCCESS|| oGetRootDeviceByTestBedGIDRes.Document.Count<2)
{
ClogService.Instance.Debug("shit -- 3实验之中测试床Name:" + strTestBedName + "2完成异常0");
//这里很重要的一点,每一次return前一定要记得释放线程,否则这个一直会占用资源
semaphore.Release();
return;
//需要注意:Semaphore对象的数量需要根据服务器的性能来设定;System.Threading.Tasks.Parallel.ForEach这种方式表示同时开启
//lstTestBed.Length个线程去做一件时间可以理解为
foreach (var item in lstTestBed)
{
Thread oThread = new Thread(new ThreadStart({ }));
}
/*
多线程里面还有一个值得一说的SpinWait类,用于提供对基本自旋的等待的支持。也就是说支持重复执行一个委托,直到满足
*/
}
});
}
}
}