In C# you can create a thread on the fly by passing a method to the thread instance.
TextBox textBox1
private void method()
{
Thread demoThread = new Thread(dowork);
demoThread.Start();
}
private void dowork()
{
//do stuff
}
If you want to change the local variable e.g textBox1 as follows:
private void dowork()
{
//do stuff
textBox1.Text = "hello";
}
The program will fail and complain about the call is not Thread Safe.
Instead, you should create a SetText method and a delegate of the method to do the work.
"A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure"
delegate void delegate_SetText(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
delegate_SetText ds = new delegate_SetText(SetText);
this.Invoke(ds, text);
}
else
{
this.textBox1.Text = text;
}
}
private void dowork()
{
//do stuff
SetText("hello");
}
In this way, the thread set text through a method which invokes a delegate to get the work done.