We're having trouble writing the code to update a UI control (label.Text)
from a secondary thread. We're using C# with Windows Forms.
We have a main form named MainForm, a splash screen form named SplashScreen,
and a C# class library named BackgroundProcess.
On application start, we simply want to show the splash screen form, kick
off the background processing on a separate thread, and, at different points
in the background processing, update a label on the splash screen to inform
the user of what the application is doing. When the processing is done, the
splash screen form goes away and the main form appears.
In the main form's form load event we have:
private void MainForm_Load(object sender, System.EventArgs e)
{
// Create and show the splash screen
SplashScreen frmSS = new SplashScreen();
frmSS.Show();
// Create the object for background processing and set an initial
property
BackgroundProcess bp = new BackgroundProcess();
bp.StartingDirectory = @"C:\";
// Create a new thread for the background processing and start it
System.Threading.Thread activeThread = new System.Threading.Thread(new
System.Threading.ThreadStart(bp.StartProcess));
activeThread.Start();
while (activeThread.IsAlive)
{
Application.DoEvents();
}
// Clean up
activeThread = null;
bp = null;
frmSS.Close();
frmSS = null;
}
This code works, and the code in our class library (i.e., the background
processing code) works, but we still can't get the splash screen's label to
update.
We've trying using delegates/events, etc. and have not been successful in
getting the label updated from the secondary thread that's doing all the
"behind-the-scenes" processing.
Any suggestions?
Thanks.