I have a Windows Form, which is a modal mdi child, that is suppose to be shown when some intense background work is going on, so the user cannot use any of the controls until that work is finished.
It is very simple, here is the code.
public partial class ProgressForm : Form
{
private int periodCount = 5;
public ProgressForm(String message)
{
InitializeComponent();
messageLabel.Text = message;
}
public void startThread()
{
Thread t = new Thread(new ThreadStart(doWork));
t.IsBackground = true;
t.Start();
}
void doWork()
{
while (true)
{
if (periodCount == 5)
{
periodCount = 1;
}
else
{
periodCount++;
}
switch (periodCount)
{
case 1: periodsLabel.Text = "."; break;
case 2: periodsLabel.Text = ". ."; break;
case 3: periodsLabel.Text = ". . ."; break;
case 4: periodsLabel.Text = ". . . ."; break;
case 5: periodsLabel.Text = ". . . . ."; break;
}
}
}
}
but, the periodsLabel.Text does not change as it is suppose to! How do I get it to update the UI while doing something else in the background?
ProgressForm progressForm = new ProgressForm("Your database data is being exported, please wait.");
progressForm.ShowDialog();
progressForm.startThread();
First, in my humble opinion, you should not just throw away a thread like you do.
The best practice is using a
BackgroundWorkerThread.Second, you form isn’t modal at all, as you only show it using the
Show()method. In order to make it a modal form, you need to make it a dialog using theShowDialog()method.As to why exactly your Form is crashing is quite out of scope from now on. Please consider following the following steps:
BackgroundWorkerclass;BackgroundWorker.DoWork()method do the dirty work for you;BackgroundWorker.WorkerReportsProgress = truein the component model property window in design;ReportProgress()using theReportProgress(int)method.Please see this question (C#: Populating a UI using separate threads.) and my code sample which simply explains, I think, the use of a BackgroundWorker class instance.
Note: Still looking for another example.
EDIT #1
Here’s a good article on threads: Threading in C#.
‘Cause
Jon Skeetsaid so! Multi-threading in .NET: Introduction and suggestions.