0

In short, I have 2 main questions:

1 - Is there any possible way to use the Send() method from the Ping class indefinitely?

2 - Will this cause the computer to significantly slow down?

I'm making a program that will in short establish an average ping to a certain server and inform the user whenever the ping(ms) increases above a certain point over the average. Now, to accomplish this I would naturally have to have the program ping said server forever (until the program closes of course).

If there is no way I could do this forever, I can only think of having an unreasonably large for loop or a while (true) {} loop.

I'm just concerned this will cause significant strain on the user's computer. Can this be confirmed or am I just too cautious?

Chaost
  • 137
  • 3
  • 12
  • "I'm just concerned this will cause significant strain on the user's computer. Can this be confirmed or am I just too cautious?" - why would it cause strain? Consider how IO works on a computer. – Dai Apr 25 '18 at 21:07
  • 2
    A while loop with a short sleep between pings doesn't sound like an issue to me. – Blake Thingstad Apr 25 '18 at 21:07
  • I was thinking this wouldn't be an issue myself, but as I'm still in the learning phase of optimizing my programs and learning how to program efficiently I was just concerned this would take far too much processing power, so I thought I'd find out whether this is a bad idea or not before writing all the code for it – Chaost Apr 25 '18 at 21:10
  • You can also start a cmd process and redirect the output to get the ping results, as a another option. https://stackoverflow.com/questions/206323/how-to-execute-command-line-in-c-get-std-out-results – Sorceri Apr 25 '18 at 21:15
  • @Sorceri I was considering that until I found out .NET actually has a class for this, using the Async method suggested below seems more efficient – Chaost Apr 25 '18 at 21:18

1 Answers1

2

If you want to be super-efficient, use Async IO - that way your application can re-use existing threads without needing to handle blocking calls (and thus needlessly consuming threads):

public async Task PingForeverAsync( IPAddress host )
{
    Ping ping = new Ping();
    while( true )
    {
        Task interval = Task.Delay( 5000 );
        Task<PingReply> pingTask = ping.SendAsync( host, 5000 );

        PingReply reply = await pingTask.ConfigureAwait(false);
        // (Measure the reply time here and send out notification if necessary)

        await interval.ConfigureAwait(false); // await the 5000ms interval delay
    }
}
Dai
  • 141,631
  • 28
  • 261
  • 374