I’m new to this thread world. I saw bunch of tutorials regarding thread but I still find it difficult to use the way i want. What i want is to update a Label right after i got Ping result. The codes below is the working well except it updates all labels at a time after all the ping results are returned. I think using Thread can help me with this.
for (int i = 0; i < lblPings.Count; i++)
{
Ping x = new Ping();
if (txtTo[i].Text.Length > 0)
{
PingReply reply = x.Send(IPAddress.Parse(txtTo[i].Text));
if (reply.Status == IPStatus.Success)
{
lblPings[i].Text = reply.RoundtripTime.ToString() + "ms";
lblPings[i].ForeColor = Color.Blue;
}
else //if host is not reachable.
{
lblPings[i].Text = "Failed";
lblPings[i].ForeColor = Color.Red;
}
}
}
It will help here to understand what is going on behind the scenes.
When you set a property on a control, you are not telling that control to redraw itself. Instead, two things happen: you change the data the control will use when it redraws itself later anyway, and you send a message to the window system that this control is out of date. You now have to wait for the windowing system to come back and re-paint the control before any update happens.
The problem here is that any re-painting happens on the same thread that your event handlers and other normal code uses. This means that you can’t possibly update the control using what you think of as normal code until after your entire method has completed and control flow on that thread goes back to the windowing system.
There are a few different ways you can get around this problem, such as DoEvents or Invoke, but I think most of the time the best fit for a Winforms app is to use the BackgroundWorker control.