Monitoring internet connection at run time

2

I'm using this method in C # to be able to identify whether the computer is connected to the internet or not

    private bool VerificarConexao()
    {
        if (NetworkInterface.GetIsNetworkAvailable()) {
            return true;
        }
        else{
            return false;
        }
    }

The method only runs when it's called, but I wanted it to run automatically (every 30 seconds) as if it were in the background. What is the best way to address this issue?

    
asked by anonymous 16.12.2016 / 13:15

2 answers

7

For this purpose you can use the FluentScheduler ...

using FluentScheduler;

public class MyRegistry : Registry
{
    public MyRegistry()
    {
       //executa o código a cada 30 segundos
       Schedule<SeuMetodo>().ToRunNow().AndEvery(30).Seconds();
    }

} 
    
16.12.2016 / 13:31
2

There are several ways a simple one would look like this:

using static System.Console;
using System.Timers;

public class Program {
    public static void Main() {
        var aTimer = new Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimed);
        aTimer.Interval = 30000;
        aTimer.Enabled = true;
        ReadLine();
    }

    private static void OnTimed(object source, ElapsedEventArgs e) {
        if (NetworkInterface.GetIsNetworkAvailable()) {
            //faz alguma coisa aqui
        } else {
            //pode fazer algo se a rede caiu
        }
    }
}

See running on CodingGround .

Note that you can not return whether it is active or not. Are you going back to whom? Who called right? Who called was Timer . He does not know what to do with this return, he can not do anything. So the right thing is to do something right there.

Actually there is little or no gain in doing this. Why do you need to check to see if the connection is active? If it really makes sense to do this, the correct thing is to take an action on the method itself which is called every 30 seconds. If in fact you need to know if the connection is active before doing any operations, then it is best to keep the function you created and call it when you need it. Or better still try to do what you want, if the network fails, you treat it and avoid a race condition .

private bool VerificarConexao() {
    return NetworkInterface.GetIsNetworkAvailable();
}

This does not check the internet, it checks the network.

    
16.12.2016 / 13:48