I have a Form with a Label with text “Loading”.
label1.Text = "Loading...";
In Form.Load I have a new Thread which is doing something, lets say this.
void Form_Load(object sender, EventArgs args)
{
Thread t = new Thread(run);
t.Start();
}
void run()
{
for(int i = 0; i < 1000000; i++)
{
}
}
I want to change label1.Text property to “Finished” after the completion of Thread “t”. But where and how to change I don’t have any idea. I am learning Threads. Do I have to create one more thread to do this which continouously checks the isAlive property of Thread “t”?
You have multiple solution. If you really want to use the Thread class, you can call the Join method, but this will block the UI thread which is not a good thing. You could also call the Invoke method of your form right after your “for” loop as so
The invoke method is required because you are in a windows form and the invoke method will execute your code on the UI thread.
Instead of using the Thread class, you could also have a look at Delegate.BeginInvoke and at System.Threading.Tasks. They are both more efficient since it pool the threads and the provide callback to separate your tear-down code.