Solution for runtime error while repeatedly calling Ping.Send from C#

If you are using .NET Framework 2.0 or .NET Framework 3.5, and getting unexpected Runtime Error while repeatedly calling the System.Net.NetworkInformation.Ping.Send method from C# code, this is due to an issue which got resolved in .NET Framework 4.0 and above.


Today, we are going to discuss about the issue, the root cause and the workaround to resolve this issue targeting .NET Framework version older than 4.0.


Solution for runtime error while repeatedly calling Ping.Send from C# (www.kunal-chowdhury.com)


According to Microsoft help documentation, you may get unexpected runtime error or access violation exception when calling System.Net.NetworkInformation.Ping.Send repeatedly by creating and destroying the instance of the System.Net.NetworkInformation.Ping class.


It has been also noticed that, if you are continuously calling the Send method, it occasionally fails even before the timeout expires and returns System.Net.NetworkInformation.IPStatus.TimedOut as the response.


The issue can happen only in applications targeting .NET Framework 2.0, 3.5. If you are using .NET Framework 4.0 or above, the problem does not occur.

Solution (Workaround)

To resolve this issue, as a workaround, you can follow either of the following listed options:

  • Microsoft recommends to upgrade your solution to .NET 4.0 or above.

  • Change your implementation, so that, it does not create and destroy the Ping class object repeatedly. For this, move out the object creation out of the loop; or create the static instance of the class and use it globally, across the application. Here's a sample implementation of the code:

    Ping pingRequest = new Ping();
    PingReply pingResponse;
        pingResponse = pingRequest.Send("www.kunal-chowdhury.com");

  • Alternatively, you can call the GC.KeepAlive on the Ping class object and ask the garbage collector not to destroy it. By calling this, the cause of the problem will be eliminated and the Access Violation Exception can be avoided. Here's the sample code on how to call the GC.KeepAlive method:

        Ping pingRequest = new Ping();
        PingReply pingResponse = pingRequest.Send("www.kunal-chowdhury.com");

I hope, if you are facing this issue, either of the above solutions will help you to resolve the error in your application. In case you are still facing it, try clubbing them. For my case, I was able to resolve it by setting a static object reference of the Ping class and calling the GC.KeepAlive method, after every Send call. What was the solution for your case?



Kunal Chowdhury
If you have come this far, it means that you liked what you are reading (Solution for runtime error while repeatedly calling Ping.Send from C#).

Why not reach little more and connect with me directly on Twitter, Facebook and LinkedIn. I would love to hear your thoughts and opinions.

Authored Books: