Let's say, I have two buttons on a windows form. When I press button1, I use an AutoResetEvent called wh inside a new thread th in order to wait. When I press button2, I do wh.Set() so that my thread th is unlocked. Here is my class to illustrate this:
public partial class Form1 : Form
{
AutoResetEvent wh = new AutoResetEvent(false);
Thread th;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
th = new Thread(thread);
th.Start();
}
public void thread()
{
MessageBox.Show("waiting..");
wh.WaitOne();
MessageBox.Show("Running..");
}
private void button2_Click(object sender, EventArgs e)
{
wh.Set();
}
}
This is working as wanted. But my problem is that I can't access, let's say a label or any other control, from my thread th..
public partial class Form1 : Form
{
AutoResetEvent wh = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
}
Thread th;
public void button1_Click(object sender, EventArgs e)
{
th = new Thread(thread);
th.Start();
}
public void thread()
{
label1.Text = "waiting..";
wh.WaitOne();
label1.Text = "running..";
}
private void button2_Click(object sender, EventArgs e)
{
wh.Set();
}
}
I get an error running this, saying that label1 is accessed from another thread.
So how can I access controls in my second thread, or modify my code to change the location of the wh.WaitOne
, whithout blocking the main thread?
Code examples are appreciated!