It has several forms a simple would be 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
}
}
}
I put in the Github for future reference.
Note that you cannot return whether you are active or not. Will you return to whom? Who called right? Who called was the Timer
. He doesn’t know what to do with that return, he can’t do anything. So the right thing is to do something in there.
Actually there is little or no gain in doing this. Why do you need to keep checking if the connection is active? If it really makes sense to do this, it is right to take an action in the method itself that is called every 30 seconds. If in fact what you need is to know if the connection is active before doing any operation, then it is best to keep the function you had 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 running condition.
private bool VerificarConexao() {
return NetworkInterface.GetIsNetworkAvailable();
}
It doesn’t check the internet, it checks the network.
Why do you need this? What kind of application will you use? It’s probably a mistake to do this. Even if you do, just use
return NetworkInterface.GetIsNetworkAvailable()
– Maniero
Why a mistake do this? I want to know if my internet connection is active or not through my system ...
– Bruno
This you have already written, if you can answer what I asked, I can help more.
– Maniero
I answered what you asked in the comment above, did not understand ?
– Bruno
Observing:
NetworkInterface.GetIsNetworkAvailable()
does not check if the computer is connected to the internet and yes if it has any network connection available to connect. To check if there is a connection, I suggest using theSystem.Net.NetworkInformation.Ping
to achieve a specific field.– CypherPotato