I want to learn more about threading and created a little test application that change the backcolor of a label.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//lblColor
public Color theLabel
{
get { return this.lblColor.BackColor; }
set { this.lblColor.BackColor = value; }
}
//btnStart
private void btnStart_Click(object sender, EventArgs e)
{
ThreadTest cColor = new ThreadTest();
Thread tColor = new Thread(new ThreadStart(cColor.ChangeColor));
tColor.Start();
}
}
And…
public class ThreadTest
{
public void ChangeColor()
{
Form1 foo = new Form1();
while (true)
{
foo.theLabel = Color.Aqua;
foo.theLabel = Color.Black;
foo.theLabel = Color.DarkKhaki;
foo.theLabel = Color.Green;
}
}
}
The only problem is why can’t i make this code work? I can see that the code in ChangeColor runs but the color of the label don’t change.
At first glance, you are constructing a new form
inside ThreadTest and never displaying the form, my guess is you intended to change the form color on the form with btnStart? You have two options, either pass in the form in to a ParameterizedThreadStart or re-write the code to just operate on the existing form.
Also, based on the code written, you will likely need to use Invoke to update the state of the form as you cannot have worker threads update the UI. I will tweak your code and posted a revised example if someone doesn’t beat me to it.
Edit
In this case you don’t need the invoke… but here is what I think you were intending…
Also, it is important to set worker threads as background threads, otherwise when you close the form, the thread will keep that appliaction open.
Additional Example
A slightly different example would be to have multiple threads trying to update the same value and see how they are interleaved… simple snippet to get the ball rolling.