Assuming the constructive criticism in this thread Thread-safe events - is this a "clean" way? I sat down and tried to read me in the whole thematics of multithreading.
Here's some code with the same base question: Is this an established way to create a non-freezing UI using events?
public partial class Form1 : Form
{
public delegate void MyThreadUpdateHandler(string s);
public event MyThreadUpdateHandler MyThreadUpdate;
System.Threading.Thread MyThread;
public Form1()
{
InitializeComponent();
}
void DoTheCount()
{
int a = 0;
while (a < int.MaxValue)
{
if (a % 1000000 == 0)
{
this.MyThreadUpdate(a.ToString());
}
a++;
}
}
private void Form1_MyThreadUpdate(string s)
{
this.lblEvent.Invoke((MethodInvoker) delegate ()
{
lblEvent.Text = s;
});
}
private void btnStartThread_Click(object sender, EventArgs e)
{
MyThreadUpdate += Form1_MyThreadUpdate;
if (MyThread == null)
MyThread = new System.Threading.Thread(new System.Threading.ThreadStart(DoTheCount));
lblStatus.Text = "Starting thread";
if (MyThread.ThreadState == System.Threading.ThreadState.Unstarted)
MyThread.Start();
}
private void btnAbortThread_Click(object sender, EventArgs e)
{
MyThread.Abort();
}
}
However there's something I still don't get. Why are some examples using a Program() like this one? http://www.codeproject.com/Articles/667298/Using-ThreadStaticAttribute
Thank you :)