How to convert "WebClient" to "async / await"?

1

I have code that checks to see if it has 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 the 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;
    }
}

Code above gives error: "Can not wait for void".

Using the "Ping" class: (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;
    }
}
    
asked by anonymous 18.02.2018 / 16:04

1 answer

1

You must use the OpenReadTaskAsync method, this has async / await support, OpenReadAsync already existed before async / await, and triggers an event when the operation completes, I believe that so they had to give this other method name to support async / await

Another detail is that the return of an async method should always be a Task

public async Task<bool> InternetIsConnected()
{
    try
    {
        using (var client = new WebClient())
        {
            Uri uri = new Uri("http://clients3.google.com/generate_204");
            using (await client.OpenReadTaskAsync(uri))
            {
                return true;
            }
        }
    }
    catch
    {
        return false;
    }
}
    
18.02.2018 / 23:07