C# Ping crashes entire program

Go To StackoverFlow.com

0

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...");
}
2012-04-03 21:17
by dtyler
Have a look at the StackTrace of the InnerException of the TargetInvocationException to find out where the exception comes from - dtb 2012-04-03 21:19
Or try using Send instead on a seperate threa - huysentruitw 2012-04-03 21:25
Check your PingCompletedEventHandler. You're doing this async, so not everything occurs inside your try catch block. Your event will spawn separately - JamieSee 2012-04-03 21:30


2

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.

2012-04-03 22:44
by Hans Passant


0

Well since your exception handler is not getting hit, it must be in the other part of your code where the error is occuring.

2012-04-03 21:19
by Sam Axe
SendAsync can throw an exception outside the try/catch bloc - huysentruitw 2012-04-03 21:24
It doesn't matter how hard you try to get someone to think for themselves.. someone else always has to ruin the ending - Sam Axe 2012-04-03 21:25
Ads