Access Violation Exception may be thrown when you call the Ping.send method repeatedly.


Symptoms


When you create and destroy a Ping class object repeatedly in the Microsoft products listed in the "Applies to" section, this may result in an unexpected Runtime Error such as Access Violation Exception depending on the application configuration or when the System.Net.NetworkInformation.Ping.Send method is called.

Ping Class

Cause


When an application creates and destroys a Ping object repeatedly, some objects that are internally retained by the Ping class are recognized as a not referred object, which are then destroyed by the garbage collection mechanism. This may cause an unexpected Runtime Error or Access Violation Exception depending on the implementation of the application or the timing of the Ping.Send method being called.

For example, with the implementation described below, it is likely that the Runtime Error occurs.
static void Pinger()
{
     while(true)
     {
           System.Net.NetworkInformation.Ping objping = new System.Net.NetworkInformation.Ping();
           System.Net.NetworkInformation.PingReply objPingReply;
           objPingReply = objping.Send("127.0.0.1");
    }
}


Resolution


You can workaround this problem by using either of the following options:
1)    Use the GC.KeepAlive method.
2)    Change the implementation so that it does not create and destroy a Ping class object repeatedly.
3)    Use .NET Framework 4.0.


1) Use the GC.KeepAlive method.


Use GC.KeepAlive to tell the garbage collector not to destroy a Ping class object.
This prevents the Ping class and any class objects that it internally retains from being destroyed by the garbage collector until GC.KeepAlive exists. As a result, the cause of the problem is eliminated and the Access Violation Exception can be avoided.
static void Pinger()
{
     while(true)
     {
           System.Net.NetworkInformation.Ping objping = new System.Net.NetworkInformation.Ping();
           System.Net.NetworkInformation.PingReply objPingReply;
           objPingReply = objping.Send("127.0.0.1");
           GC.KeepAlive(objping);
    }
}
Reference:
GC.KeepAlive Method

2) Change the implementation so that it does not create and destroy a Ping class object repeatedly.


Create a single Ping class object outside a loop, and keep using the single object. This prevents a Ping class object from being created and destroyed repeatedly.

For example, write the code as below:
static void Pinger()
{
    System.Net.NetworkInformation.Ping objping = new System.Net.NetworkInformation.Ping();
    System.Net.NetworkInformation.PingReply objPingReply;
     while(true)
     {
           objPingReply = objping.Send("127.0.0.1");
      }
}

3) Use .NET Framework 4.0.

This problem does not occur with .NET Framework 4.0.
We recommend updating your Visual Studio 2010 system so that you can use .NET Framework 4.0.