利用多线程实现对网站状态的监控
时间:2010-12-01 来源:clound
核心代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.NetworkInformation; using System.Collections; using Super.Ft.IDAL; using Super.Ft.DBFactory; using Super.Ft.Entity; using System.Data; using System.Threading; using System.Net; using System.IO; namespace Super.Ft.BLL { public class ThreadPing { public SiteConditionEntity SCEntity { get; set; } public SiteInfoEntity SiteEntity { get; set; } public ThreadPing(SiteInfoEntity s) { SiteEntity = s; SCEntity = new SiteConditionEntity(); } public void search() { Ping p = new Ping(); SCEntity.Siteinfoid = SiteEntity.SiteInfoID; SCEntity.SiteUrl = SiteEntity.SiteUrl; SCEntity.SiteName = SiteEntity.SiteName; SCEntity.MonitorDate = DateTime.Now; SCEntity.ADDTIME = DateTime.Now; try { PingReply reply = p.Send(SiteEntity.SiteUrl.Replace("http://", string.Empty).Replace(" ", "")); StringBuilder sbuilder = new StringBuilder(); if (reply.Status == IPStatus.Success) { SCEntity.Delaytime = reply.RoundtripTime;//延时 SCEntity.MonitorCondition = reply.RoundtripTime "正常"; } else { SCEntity.Delaytime = 0; SCEntity.MonitorCondition = "ping不通"; ////异常记录 //try //{ // WebClient web = new WebClient(); // Stream data = web.OpenRead(SiteEntity.SiteUrl); // SCEntity.Delaytime = 0; // SCEntity.MonitorCondition = "正常"; //} //catch (Exception) //{ // SCEntity.Delaytime = -1; // SCEntity.MonitorCondition = "异常"; //} // byte[] buffer = web.DownloadData(SiteEntity.SiteUrl); // string aa = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer); //if (aa.Length > 0) //{ // SCEntity.Delaytime = 0; // SCEntity.MonitorCondition = "正常"; //} //else //{ // SCEntity.Delaytime = -1; // SCEntity.MonitorCondition = "异常"; //} } } catch { //异常记录 SCEntity.Delaytime = -1; SCEntity.MonitorCondition = "异常"; } } } public class ThreadManage { Thread[] t; public List<SiteInfoEntity> SiteEntityList { get; set; } public List<SiteConditionEntity> SCEntityList { get; set; } public ThreadManage(List<SiteInfoEntity> list) { t = new Thread[list.Count]; SiteEntityList = list; SCEntityList = new List<SiteConditionEntity>(); } public void Start() { ThreadPing wp; for (int lIdx = 0; lIdx < SiteEntityList.Count; lIdx++) { wp = new ThreadPing(SiteEntityList[lIdx]); SCEntityList.Add(wp.SCEntity); t[lIdx] = new Thread(new ThreadStart(wp.search)); // start the Thread object, which executes the search(). t[lIdx].Start(); } for (int lIdx = 0; lIdx < SiteEntityList.Count; lIdx++) { // waiting for all the Threads to finish. t[lIdx].Join(); } } } }
前段调用如下:
public static List<SiteConditionEntity> LiveMeshPingSiteInfo() { List<SiteInfoEntity> SiteEntityList = SiteInfoBLL.LoadSiteList(); DateTime lStarted = DateTime.Now; ThreadManage tm = new ThreadManage(SiteEntityList); tm.Start(); TimeSpan _timeSpent = DateTime.Now.Subtract(lStarted); return tm.SCEntityList; }
相关阅读 更多 +