Introduction
This article shows the difference between running a function on the main form thread, and on a separate thread. You can thus still interact with the form even though the code would normally 'block' execution.
Background
I helped a mate out and thought this is a good example as it demonstrates just threading and nothing else.
Using the code
Just download and compile the code. Here is the important code (about five lines below, and is taken from the source code comments):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadExample te = new ThreadExample();
te.iIntervalInMilliSeconds = 5000;
Thread th = new Thread(new ThreadStart(te.Start));
th.Start();
}
private void button2_Click(object sender, EventArgs e)
{
ThreadExample te = new ThreadExample();
te.iIntervalInMilliSeconds = 5000;
te.Start();
}
}
public class ThreadExample
{
public int iIntervalInMilliSeconds = 1000;
public void Start()
{
for (int iLoop = 0; iLoop < 3; iLoop++)
{
Interaction.Beep();
Thread.Sleep(iIntervalInMilliSeconds);
}
MessageBox.Show("End");
}
}
Threading is good when you want to carry on doing something else whilst your computer slaves away in the background.
History
- V1.0 - The beginning (and the end) - Enjoy.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.