日期:2014-05-18  浏览次数:20855 次

为什么采用异步方式ping局域网内存会不断增加
功能为:监测局域网机器上线、在线、下线,采用ping的异步调用方法,用timer组件每隔一段时间ping局域网内所有计算机一次,但是每ping一次内存都要增加个3m左右,采用gc.collection()去释放内存也不行,不知是什么原因,请高手指点。代码如下:

  private void timer1_Tick(object sender, EventArgs e)
  {
  PingEmployees();
  }
  public void PingEmployees()
  {
   
  try 
{
  foreach( GHPersonInfo person in m_PersonScanArray ) //GHPersonInfo 为自定义类,
  {
  Ping myPing = new Ping();
  myPing.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
   
  string pingIP = person.IpAddress;
  int timeout = 256;
  string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
  byte[] buffer = Encoding.ASCII.GetBytes(data);
  PingOptions options = new PingOptions(32, true);
  myPing.SendAsync(pingIP, timeout, buffer, options);
  }

catch(Exception exc)
{
MessageBox.Show( "Exception: " + exc.Message);
}

  }

  public void PingCompletedCallback(object sender, PingCompletedEventArgs e)
  {
  // If the operation was canceled, display a message to the user.
  if (e.Cancelled)
  {
  txtInfo.Text += "Ping canceled.";
  }

  // If an error occurred, display the exception to the user.
  if (e.Error != null)
  {
  txtInfo.Text += "Ping failed:";
  txtInfo.Text += e.Error.ToString();
  }
  PingReply reply = e.Reply;
  if (reply == null)
  return;

  if (reply.Status == IPStatus.Success)
  {
  GetEmployeesStatus(reply.Address.ToString(), IPStatus.Success.ToString()); //如果ping通,那么据当前时间,记录局域网机器的状态
  }

  }


------解决方案--------------------
GHPersonInfo 为自定义类
这个做了什么事?看到不到
------解决方案--------------------
把那一句

GetEmployeesStatus(reply.Address.ToString(), IPStatus.Success.ToString()); 

注释掉看看。
------解决方案--------------------
如果你发现某种操作不会使“每ping一次内存都要增加个3m左右”了,那么要注意,许多操作应该“copy”PingCompletedEventArgs e返回的数据,而不是直接拿它的返回值传出去。