我做了一个小工具,每隔三十秒监测在线ip,用ping扫描局域网内的ip,得到在线的ip。但是出现一个问题大概运行十个小时后出现资源不足的问题,内存在时间长之后,被占用太多。为了验证是我的ping的问题,我把定时器改为500ms监测一次。结果内存成指数增长。我以为超时的那些都会被gc回收。但是好像没有。我百度了一下,没有找到解决办法。
public void StartScanIP()
{
//String []data= new String[2];
//扫描的操作
Ping myPing=null;
try
{
for (int i = 0; i < 255; i++)
{
myPing = new Ping();
//转换成IP地址
myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
pingIP = "192.168.2." + i.ToString();
myPing.SendAsync(pingIP, 1000, null);
}
}
catch
{
}
finally
{
myPing.Dispose();
}
}
public Dictionary<String, String> IPList = new Dictionary<string, string>();
private void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
if (!IPList.TryGetValue(e.Reply.Address.ToString(), out vlaue))
{
IPList.Add(e.Reply.Address.ToString(), "IP");
}
else
{
Console.WriteLine(e.Reply.Address.ToString() + "IP已经存在");
}
//Console.WriteLine(e.Reply.Address.ToString() + "|" + Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName);
}
}
定时器调用
private void timer2_Tick(object sender, EventArgs e)
{
Console.WriteLine("wifi在线监测");
this.timer2.Stop();
inout.OnLineCheck();
this.timer2.Start();
}