1
I have code that checks if you have the internet or not.
public static bool InternetIsConnected()
{
try
{
using (var client = new WebClient())
{
using (client.OpenRead("http://clients3.google.com/generate_204"))
{
return true;
}
}
}
catch
{
return false;
}
}
How to convert code to async/await
?
Update:
Attempt 1: (Comment from @Virgilio Novic)
public async bool InternetIsConnected()
{
try
{
using (var client = new WebClient())
{
Uri uri = new Uri("http://clients3.google.com/generate_204");
using (await client.OpenReadAsync(uri))
{
return true;
}
}
}
catch
{
return false;
}
}
Above code gives error: "Unable to wait void".
Using the class "Ping": (Functional)
private async Task<bool> InternetIsConnected()
{
Ping ping = new Ping();
try
{
await ping.SendPingAsync("google.com", 3000, new byte[32], new PingOptions(64, true));
return true;
}
catch (Exception)
{
return false;
}
}
related: https://msdn.microsoft.com/pt-br/library/ms144211(v=vs.110). aspx
– novic
@Virgilionovic I tried to do, it gives error, says it is not possible to wait void.
– Matheus Miranda
public async Task<bool> InternetIsConnected()
that’s the way it is– novic
Other Reading: https://stackoverflow.com/questions/25051674/how-to-wait-for-webclient-openreadasync-to-complete
– novic
@Virgilionovic, updated post. See what the class thinks
Ping
. Or better to useWebClient
?– Matheus Miranda
what I usually do, is run in or another Thread, and it will not be necessary to use the await.
– isaque
@Text can give me an example of code ?
– Matheus Miranda
@Matheusmiranda
void nome_da_void(){webclient.OpenRead(xxx);/*isso não 'trava seu código'*/} void NOME_OUTRA_VOID(){Thread th = new Thread(nome_da_void);th.Start();}
– isaque
@More how I will get the return of true or false ?
– Matheus Miranda
@Matheusmiranda you can create a bool, and put a Try and catch (as you did in the code of your question); if the catch is called, that bool will be false.
– isaque