多线程同步

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类,用于提供对基本自旋的等待的支持。也就是说支持重复执行一个委托,直到满足
     */

            }
        });
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值