S
SMJT
Folks,
I need some help understanding threads in .NET. I've only used the
background component worker up till now which is fine but now I need
to use multiple threads for an application which does lots of
processing.
I'm trying to start a thread from a form and part of this thread
updates a label on the form. For my simplified example I have a
single label (named label1) and a single button (named button1) on a
form, my code is below.
My code works fine, until I uncomment the line "theThread.Join()" in
the button1_Click event. If I uncomment this line, the program appears
to stall, i.e. nothing happens, the labels text is unchanged. Why is
this? Is the thread dead-locked? Is is it that I'm just doing
something silly?
Any help is much appreciated.
SMJT
using System;
using System.Windows.Forms;
using System.Threading;
namespace Simple_threadEx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart op = new ThreadStart(LoopDeLoop);
Thread theThread = new Thread(op);
theThread.Start();
//theThread.Join();
}
private void LoopDeLoop()
{
for (int i = 1; i <= 100; i++)
{
SetText(i.ToString() + "% completed.");
Thread.Sleep(20);
}
}
public delegate void SetTextDelegate(string t);
public void SetText(string t)
{
if (label1.InvokeRequired)
{
SetTextDelegate del = new SetTextDelegate(SetText);
this.Invoke(del, new object[] { t });
}
else
label1.Text = t;
}
}
}
I need some help understanding threads in .NET. I've only used the
background component worker up till now which is fine but now I need
to use multiple threads for an application which does lots of
processing.
I'm trying to start a thread from a form and part of this thread
updates a label on the form. For my simplified example I have a
single label (named label1) and a single button (named button1) on a
form, my code is below.
My code works fine, until I uncomment the line "theThread.Join()" in
the button1_Click event. If I uncomment this line, the program appears
to stall, i.e. nothing happens, the labels text is unchanged. Why is
this? Is the thread dead-locked? Is is it that I'm just doing
something silly?
Any help is much appreciated.
SMJT
using System;
using System.Windows.Forms;
using System.Threading;
namespace Simple_threadEx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart op = new ThreadStart(LoopDeLoop);
Thread theThread = new Thread(op);
theThread.Start();
//theThread.Join();
}
private void LoopDeLoop()
{
for (int i = 1; i <= 100; i++)
{
SetText(i.ToString() + "% completed.");
Thread.Sleep(20);
}
}
public delegate void SetTextDelegate(string t);
public void SetText(string t)
{
if (label1.InvokeRequired)
{
SetTextDelegate del = new SetTextDelegate(SetText);
this.Invoke(del, new object[] { t });
}
else
label1.Text = t;
}
}
}