The first thing I suggest you do is read Jon Skeet's essay on threading in WinForms: [
^]; it's a few years old, but is a "classic."
Second, I suggest you realize that while you can "get away" with what you are doing now, without implementing a real "callback mechanism" that allows you to update the Form (the Main Form, I assume) UI without producing a cross-thread UI update error of the type described in Skeet's essay, you are not going to be able to avoid clicking on the Main Form again to re-establish Focus.
So, what to do ?
I recommend you consider using a BackGroundWorker in this case, which provides a handy method to notify you when the Thread has completed. There are two CodeProject articles that can assist you in understanding 'BackGroundWorker: [
^], [
^], and, of course, MSDN has a good tutorial: [
^].
Or, you can implement something like this example which does use the 'MethodInvoker method to get a "farewell message" to the UI Thread without an error, but will still require you to click on the Main Form when the secondary Form/Thread exits:
1. the Main Form 'Form1: a TextBox, 'textBox1; a Button, 'button1
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
namespace SecondaryFormByThread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 instanceOfForm2;
Thread thread;
List<int> FormData = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
ShowLoading();
}
private void ShowLoading()
{
instanceOfForm2 = new Form2();
instanceOfForm2.Form2Data = FormData;
instanceOfForm2.DataComplete = DataComplete;
thread = new Thread(new ThreadStart(() => instanceOfForm2.ShowDialog()));
thread.Start();
}
private void DataComplete(bool closeThreadOkay)
{
textBox1.Text = string.Format("finished: data count = {0}", FormData.Count);
if (thread.IsAlive && closeThreadOkay) thread.Abort();
}
}
}
2. Form2: Form2 has a TextBox, 'textBox1. I chose to make Form2 with BorderStyle.FixedToolWindow, no 'Text, and no 'CloseButton.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
namespace SecondaryFormByThread
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
this.TopLevel = true;
}
public List<int> Form2Data { set; get; }
public Action<bool> DataComplete;
private void Form2_Load(object sender, EventArgs e)
{
this.TopLevel = true;
}
protected override bool ShowWithoutActivation
{
get { return true; }
}
private void Form2_Shown(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
Form2Data.Add(i);
Thread.Sleep(50);
textBox1.AppendText("-");
}
Invoke(new MethodInvoker(Finish));
}
private void Finish()
{
DataComplete(true);
}
}
}