Checking Internet Connection Using a Task

I'm trying to do a background job that checks the internet connection without blocking the GUI (it takes 3s to test the connection to test the connection). If the panel is successful (or not), display the image (red or green according to the result).

My code:

public Image iconeConnexion;

public Image IconeConnexion
{
    get { return iconeConnexion; }
    set { iconeConnexion = value; }
}

public void myPingCompletedCallback(object sender, PingCompletedEventArgs e)
{

    if (e.Cancelled || e.Error != null)
    {
        this.iconeConnexion = WindowsFormsApplication1.Properties.Resources.red;
        return;
    }

    if (e.Reply.Status == IPStatus.Success)
        this.iconeConnexion = WindowsFormsApplication1.Properties.Resources.green;

}

public void checkInternet()
{
    Ping myPing = new Ping();
    myPing.PingCompleted += new PingCompletedEventHandler(myPingCompletedCallback);
    try
    {
        myPing.SendAsync("google.com", 3000 /*3 secs timeout*/, new byte[32], new PingOptions(64, true));
    }
    catch
    {
    }
}

      

My call on the upload form after all the controls have loaded:

Task Parent = new Task(() =>
{
    checkInternet();
    MessageBox.Show("Check");
});

//Start the Task
Parent.Start();
Parent.Wait();

      

The application starts but no images are displayed yet. I can't figure out why.

Could you help me with this?

+3


source to share


1 answer


Since there is not much information in your question, I am assuming that when trying to set a UI element from a background thread, an exception is thrown and swallowed with Task

.

Since pinging server is an IO binding operation, there is no need to spin up a new thread. This can make it easier when combined with the new async-await

keywords introduced in C # 5.

This is used Ping.SendPingAsync

:

public async Task CheckInternetAsync()
{
    Ping myPing = new Ping();
    try
    {
        var pingReply = await myPing.SendPingAsync("google.com", 3000, new byte[32], new PingOptions(64, true));
        if (pingReply.Status == IPStatus.Success)
        {
            this.iconeConnexion = WindowsFormsApplication1.Properties.Resources.green;
        }
    }
    catch (Exception e)
    {
        this.iconeConnexion = WindowsFormsApplication1.Properties.Resources.red;
    }
}

      



And call it inside the FormLoaded event:

public async void FormLoaded(object sender, EventArgs e)
{
    await CheckInternetAsync();
}

      

As a side note:

  • Execution Task

    and waiting for it immediately usually means that you are doing something wrong. If this is the desired behavior, just try running the method synchronously.

  • It is recommended to use Task.Run

    instead of new Task

    . The former returns a "hot task" (the one that has already started), and the latter returns a "cold task" (one of which is not running and is waiting for a method call Start

    ).

0


source







All Articles