c# - Checking internet connection using Task -


i trying execute background task checks internet connection without blocking gui (checking fonction requires 3s check connection). if successful (or not) panel display image (red or green according result).

my code :

public image iconeconnexion;  public image iconeconnexion {     { 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 in form load after controls loading :

task parent = new task(() => {     checkinternet();     messagebox.show("check"); });  //start task parent.start(); parent.wait(); 

application runs no images displayed far. can't find out why.

can please me on 1 ?

as there isn't information in question, assume when trying set ui element background thread exception being thrown , swallowed task.

as pinging server io bound operation, there no need spin off new thread. can make things easier in combination new async-await keywords introduced in c# 5.

this using 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 inside formloaded event:

public async void formloaded(object sender, eventargs e) {     await checkinternetasync(); } 

as side note:

  1. executing task , waiting on means you're doing wrong. if desired behavior, consider running method synchronously.

  2. it recommended use task.run instead of new task. former returns "hot task" (one started), while latter returns "cold task" (one hasn't started , waits start method called).


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -