Updating an element on a form from a different thread
Sometimes its a good idea to spawn a new thread from the GUI, to do some heavy calculation or
other time consuming task, to avoid the GUI to freeze as the task is running.
When a thread has been spawned, it would often also be nice to recieve som kind of
feedback from the calculation, of progress and status.
It’s not possible for a thread that did not create the GUI to update it, therefore we have
to make a few tweaks to make progress information from the thread appear on the GUI.
Here is an example of how it could be done.
In the GUI (windows forms):
private delegate void DoRefreshProgressText(string info);
private Label progressText = new Label(); // could be e.g. a progressbar
CheckForIllegalCrossThreadCalls = false;
Calculator calculator = new Calculator();
calculator.reportInfo += new Calculator.ReportInfo(reportInfoToGUI);
void reportInfoToGUI(string infoString) {
if (progressText.InvokeRequired) {
DoRefreshProgressText d = new DoRefreshProgressText(reportInfoToGUI);
Invoke(d, new object[] { infoString });
} else {
progressText.Text = infoString;
}
}
In the spawned thread:
public class Calculator {
public delegate void ReportInfo(string infoString);
public event ReportInfo reportInfo;
public void SomeMethodCalledByThread(string statusText) {
if (reportInfo != null) {
reportInfo(statusText);
}
}
}
Tags: c# threads guide
Twitter
Leave a Reply