T
Tom B
I've written the code below to try and figure out how threading works.
My assumption is that when starting a new thread it would run at the same
time as the original thread.
Am I wrong?
I've made a simple form with two text labels and a button. When I click the
button, it creates a thread that updates one label, and the main code
updates the other label.
It appears that the created thread doesn't run until the main thread is
done?!?
Is my code wrong? Is my logic wrong? Am I an idiot?
Thanks for taking a look
private void button1_Click(object sender, System.EventArgs e)
{
ThreadStart ts=new ThreadStart(addText);
Thread t = new Thread(ts);
t.Start();
//for (int iLoop=0;iLoop<10;iLoop++)
//{
//lblWorking.Text="";
lblWorking.Text=DateTime.Now.ToString();
lblWorking.Refresh();
//Thread.Sleep(1000);
//}
}
private void addText()
{
lblText.Text+= "Starting: " + DateTime.Now.ToString() + "\n";
//MessageBox.Show("In the thread");
for (int iLoop=0;iLoop<10;iLoop++)
{
Thread.Sleep(300);
lblText.Refresh();
}
lblText.Text+="Finishing: " + DateTime.Now.ToString() + "\n";
lblText.Refresh();
}
My assumption is that when starting a new thread it would run at the same
time as the original thread.
Am I wrong?
I've made a simple form with two text labels and a button. When I click the
button, it creates a thread that updates one label, and the main code
updates the other label.
It appears that the created thread doesn't run until the main thread is
done?!?
Is my code wrong? Is my logic wrong? Am I an idiot?
Thanks for taking a look
private void button1_Click(object sender, System.EventArgs e)
{
ThreadStart ts=new ThreadStart(addText);
Thread t = new Thread(ts);
t.Start();
//for (int iLoop=0;iLoop<10;iLoop++)
//{
//lblWorking.Text="";
lblWorking.Text=DateTime.Now.ToString();
lblWorking.Refresh();
//Thread.Sleep(1000);
//}
}
private void addText()
{
lblText.Text+= "Starting: " + DateTime.Now.ToString() + "\n";
//MessageBox.Show("In the thread");
for (int iLoop=0;iLoop<10;iLoop++)
{
Thread.Sleep(300);
lblText.Refresh();
}
lblText.Text+="Finishing: " + DateTime.Now.ToString() + "\n";
lblText.Refresh();
}