Michael
Michael

Reputation: 299

Threading in C# method with parameter using same variable

I'm a newb in programming and I'm trying to do my first thingy that would be for someone else and not just me (so shouldn't be that crappy ^^ )

It's a Online-Checker for clients in LAN network (so he can just paste a list of clients, and it returns the online or offline).

fyi: I'm using Try/Catch because ping.send to an offline host returns in an Error which crashed the application.

Currently it looks like this:

        private void btn_check_Click(object sender, EventArgs e)
    {


        string[] hosts = txt_hosts.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

        foreach (String host in hosts)
        {
            pinger(host);
        }
    }

    public void pinger(string host)
    {
        var ping = new System.Net.NetworkInformation.Ping();
        try
        {
            var result =  ping.Send(host);
            txt_result.Text += "true" + Environment.NewLine;
            Application.DoEvents();
        }
        catch
        {
            txt_result.Text += "false"+Environment.NewLine;
            Application.DoEvents();
        }

    }

Now, the interface is like frozen whenever a ping.send is processing (and that's quiet long cause of the timeout of pings).

Is there any way to do this threaded? Before I tried to start a thread, but that doesn't work either because both write in txt_result and that returns an error.

Thanks for any help!

Upvotes: 1

Views: 131

Answers (3)

Stas BZ
Stas BZ

Reputation: 1202

If use acync/await:

// send request
foreach (string host in hosts)
    pinger(host);

// async function
async void pinger(string host)
{
    var ping = new System.Net.NetworkInformation.Ping();
    bool bResp;

    try
    {
        var result = await ping.SendPingAsync(host, 4000);
        bResp = result.Status == System.Net.NetworkInformation.IPStatus.Success;
    }
    catch { bResp = false; }

    txt_result.Text += bResp.ToString() + Environment.NewLine;
}

Upvotes: 1

DidIReallyWriteThat
DidIReallyWriteThat

Reputation: 1033

Run on a background worker.

  public void pinger(string host)
  {
  var bw = new BackgroundWorker();

  bw.DoWork += delegate(object sender, DoWorkEventArgs e)
  {
      var ping = new System.Net.NetworkInformation.Ping();

     try
    {
      var result =  ping.Send(host);
      e.Result = new object[] { result};
    }
    catch(Exception ex)
    {
      // Catch specific exceptions here as needed
    }
  };

  bw.RunWorkerCompleted += (bw_txt_results);

  bw.RunWorkerAsync();

 }
private void bw_txt_results(object sender, RunWorkerCompletedEventArgs e)
 {
    txt_result = e.result[0].ToString();
 }

Upvotes: 0

Gaston Siffert
Gaston Siffert

Reputation: 372

System.Threading.Tasks.Task.Factory.StartNew(() =>
{
  pinger(host);
});

It could throw an exception at the line : txt_result.Text = "..."; Because you are trying to modify a value in a thread from another thread. So you could write:

System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
{
   txt_result.Text = "...";
}));

Which will request the UI thread to modify the value.

Upvotes: 0

Related Questions