Search code examples
c#pingdispose

How to ping, get the ping number, and put it in a label


So here is what i do:

using (Ping pingSender = new Ping())
{
   replys = pingSender.Send(otherPartyIP.Address).RoundtripTime.ToString();
}

So this is being run once a sec, but i wonder, is this really optimal. Even if ping once a sec should probably be microscopic to performance, improvement is something to strive for.

So, is this better, or will it be the same, or worse (as i think it creates a new all the time without disposing)

replys = new Ping().Send(otherPartyIP.Address).RoundtripTime.ToString();

Though, when i think of it, it should be better to create a Ping() when i start my application, and dispose of it when i end it.


Solution

  • Your two examples are identical.. except that Dispose() is called when using using.. whereas, it isn't in the second example.

    Since the Ping object is being re-used.. it is definitely a good idea to scope it much wider than you are (in what I assume is some sort of Timer). So there is no real case not to move it into a wider scope (class level perhaps).