0

i have this method to send ping for a duration.

public async Task<bool> TryToConnect(bool firstTime, int second)
{
    var valueToReturne = false;
    if (firstTime)
        await Task.Delay(1200);
    var ct = new CancellationTokenSource(TimeSpan.FromSeconds(second)).Token;
    var pingSender = new Ping();
    PingReply result;
    try
    {
        while (!ct.IsCancellationRequested)
        {
            result = await pingSender.SendPingAsync("www.google.com", 100);//null exeption
            if (result.Status != IPStatus.Success)
                continue;
            valueToReturne = true;
            break;
        }
    }
    catch (Exception)
    {
        valueToReturne = await TryToConnect(false, second / 2);
    }
    return valueToReturne;
}

For reasons I do not know. the

result = await pingSender.SendPingAsync("www.google.com", 100);

command sometimes that there is no internet access going through a null exception and the method going to the catch block befor ct ends.but i want to execute the

result = await pingSender.SendPingAsync("www.google.com", 100);

command under any circumstances for ct duration.

DiniMad
  • 49
  • 1
  • 9

1 Answers1

-2

The ping keeps retrying asynchronously even if the first ping returns an exception. Thus, a ping completed event needs to be registered so that you know for a fact that the ping was retrying until timeout. Please find the code below:

private void Form1_Load(object sender, EventArgs e)
    {
        var result = TryToConnect();
    }

    private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        if (e.Cancelled)
            return;

        if (e.Error != null)
            return;

        if (e.Reply.Status == IPStatus.Success)
        {
        }
    }

    private bool TryToConnect()
    {
        Ping myPing = new Ping();
        int timeOutMS = 5000; //5 seconds
        myPing.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
        try
        {
            myPing.SendAsync("www.google.com", timeOutMS);
            return true;
        }
        catch
        {
            return false;
        }
    }
Raviraj Palvankar
  • 879
  • 1
  • 5
  • 9
  • Exception Unhandled :System.InvalidOperationException: 'An asynchronous call is already in progress. It must be completed or canceled before you can call this method.' – DiniMad Feb 28 '18 at 07:24
  • Check the answer now, exception doesn't mean that ping is not happening, it keeps retrying and your c# will throw the exception if not handled. – Raviraj Palvankar Feb 28 '18 at 09:31