I've got a question regarding multithreading in an application. I've got 2 forms - one mainForm and one editForm. The editForm is called by the mainForm on user request. The editForm has implemented a datagrid, which should be filled by a thread. I've done it this way:
try
{
InitializeComponent();
Thread loadingDatagridThread = new Thread(new ThreadStart(() =>
{
this.LoadDataGrid();
}));
loadingDatagridThread.Name = "LoadingDatagridThread";
loadingDatagridThread.Start();
}
catch (Exception exp)
{
throw exp;
}
The "LoadDataGrid" method looks like this:
private void LoadDataGrid()
{
try
{
this.picBox_Loading.Visible = true;
if (this.InvokeRequired == true)
{
this.HaulierList = new Classes.HaulierCollection(Classes.HaulierCollectionKind.ByStopFlag, new object[] { 0 });
this.BeginInvoke(new LoadDataGridDelegate(this.LoadDataGrid));
return;
}
else
{
//Fill the grid
}
}
}
The collection of the datagrid (HaulierCollection) is being loaded while it is in the thread. The datagrid then is being filled when in the Main Thread, when InvokeRequired is false. This scenario works fine, if I work in Visual Studio and test it in Debug mode. I can close and re-open the editForm and the data of the datagrid is always being loaded. BUT if I start the EXE file of the solution from the debug folder without using Visual Studio Debug mode, the datagrid of the editForm is being filled only the first time I open it. The next times the datagrid is always empty. I found out, that this behaviour is caused by the InvokeRequired property. The first time I open the editForm it is InvokeRequired = true, but if I close the form and re-open it, it is always false. But why? I dispose the form, when the form is closed.
private void EditForm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Dispose();
}
Why is InvokeRequired always false, when re-opening the editForm? Can anybody help please?