I am building a C# windows form app that pings multiple computers by name, which the user can specify.
I am using the System.Net.NetworkInformation.Ping class and the SendAsync method, with a method to handle the result.
The issue I am having occurs when the user specifies a computer name which does not exist. Rather than Ping returning an error to my callback method, however, I get a TargetInvocationException at Application.Run(new Form()) (the main method of the entire form). I have tried surrounding relevant code with try/catch but they never seem to catch the exception
Here is relevant code for ping:
Ping p = null;
try
{
p = new Ping();
p.PingCompleted += new PingCompletedEventHandler (updateUI);
p.SendAsync(computername, 10, computername);
}
catch (Exception)
{
((IDisposable)p).Dispose();
MessageBox.Show("Ping Failed...");
}
Check the e.Error property first in your PingCompleted event handler. Trying to use the other properties when it is not null is a guaranteed kaboom. From the PingCompletedEventArgs.Error property documentation in MSDN:
If an exception is raised during an asynchronous operation, the class will assign the exception to the Error property. The client application's event-handler delegate should check the Error property before accessing any properties in a class derived from AsyncCompletedEventArgs; otherwise, the property will raise a TargetInvocationException with its InnerException property holding a reference to Error.
Well since your exception handler is not getting hit, it must be in the other part of your code where the error is occuring.