先上代码:
多线程实现ping校验:
public void PingCameraNew(List<CameraMongoDto> assetlist)
{
ThreadPool.SetMaxThreads(200, 200);
for (int a = 0, b = assetlist.Count; a < b; a++)
{
CameraMongoDto asset = assetlist[a];
bool poolkai = ThreadPool.QueueUserWorkItem(new WaitCallback(DoWorkNew), asset);
}
}
多线程执行的方法:
public void DoWorkNew(object asset)
{
try
{
CameraMongoDto cameraMongo = (CameraMongoDto)asset;
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
string data = "Test Data!";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 250; // Timeout 时间,单位:毫秒
int flag = 0;
for (int i = 0, j = 10; i < j; i++)
{
System.Net.NetworkInformation.PingReply reply = p.Send(cameraMongo.IP, timeout, buffer, options);
if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
{
flag = flag + 1;
}
}
cameraMongo.LosePacket = (10 - flag) * 10;
if (flag == 0)
{
cameraMongo.IsUsed = 1;
cameraMongo.AlarmLevel = (int)AlarmLevel.紧急;
}
else
{
cameraMongo.IsUsed = 0;
cameraMongo.AlarmLevel = (int)AlarmLevel.正常;
}
SingletonOff.Instance.Add(cameraMongo);
Lind.DDD.Logger.LoggerFactory.Instance.Logger_Debug(" --offnum:" + AlarmCount.Instance.offnum + "列表长度" + SingletonOff.Instance.Count);
if (SingletonOff.Instance.Count >= AlarmCount.Instance.offnum)
{
if (SingletonOff.Instance.Count > 0)
{
if (PingUpdata.Instance.Isused)
{
PingUpdata.Instance.Isused = false;
if (mongohelperc.CameraMongoUpList(SingletonOff.Instance))
{
AlarmHandingCameList(SingletonOff.Instance);
PingUpdata.Instance.Isused = true;
SingletonOff.Instance.Clear();
AlarmCount.Instance.offnum = 0;
}
}
}
}
}
catch (Exception ex)
{
Lind.DDD.Logger.LoggerFactory.Instance.Logger_Debug("线程执行失败!" + ex.Message + "trace:" + ex.StackTrace);
}
}
方法中没ping完一个设备,要把ping的结果存入单例的列表中,当单例的列表数大于等于需要ping的总数的时候,用一个方法把ping的结果存入数据库中,换句话说,是用列表的长度来衡量此次集体ping的所有线程是否完成。
ping的时候每一个设备循环ping十次的原因是需要保证ping的准确性,也可以把这十次ping的结果来做设备的丢包率。