System.Net.NetworkInformation.Ping crashing

我与影子孤独终老i 提交于 2019-12-10 17:36:31

问题


So, I have a site with over 600 devices. I'm trying to ping them all one by one using the standard .NET ping class. For some reason, this thread is crashing - it just stops responding after a few days. All it does is ping devices on the network. We're using Microsoft Windows Server 2008 R2. Is there any problems with the .NET ping class? I also seem to be experiencing memory leaks which I'm guessing is due to the pinging. Should I just write a win32 ping dll to do the job for me or am I doing something wrong with .NET?

private void PingDevice(out bool state, string IP)
{
    PingReply pingReply;
    System.Net.NetworkInformation.Ping pingSender = null;
    state = false;
    try
    {
        pingSender = new System.Net.NetworkInformation.Ping();
        pingReply = pingSender.Send(IP, 4000);
        state = (pingReply.Status == IPStatus.Success); // comms is on/off
    }
    catch (Exception ex)
    {
        PingGlobals.driverThread.LogIt("$E Pinging Devices:" + ex.Message + ", " + IP);
    }
    finally
    {
        if (pingSender != null)
        {
            ((IDisposable)pingSender).Dispose();
        }
    }
}

回答1:


In using the asynchronous version of Ping, I have found that sometimes Ping never returns. I could imagine that if this happens on Async, on Sync, it would just stall. The answer I have found for Async is to set up a timeout (longer than the Ping timeout), then call SendAsyncCancel before SendAsync to retry.




回答2:


Creating new instances of the System.Net.NetworkInformation.Ping class seems to leak memory on Server 2008. If you keep one (or a hundred) instances around and reuse them that problem goes away. Just be very careful accessing it from multiple threads.




回答3:


This is an issue reported for .Net versions below 3.5
There is a Microsoft article describing the issue and the solutions for it here.



来源:https://stackoverflow.com/questions/13173068/system-net-networkinformation-ping-crashing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!