Threading question "Controls created on one thread cannot be parented to a control on a different th

  • Thread starter Thread starter VMI
  • Start date Start date
V

VMI

Im using a separate thread in my code to copy a huge file, but I get the
"Controls created on one thread cannot be parented to a control on a
different thread" when I want to update the Form controls after makeBackup
is complete. I know what the problem is (I'm trying to update controls from
a thread that did not create them), but how can I fix it? This my code:

private delegate void BackupCompletedEventHandler();
private event BackupCompletedEventHandler backupCompleted;
private void btn_run_click(object sender, System.EventArgs e)
{
if (myMsgs.createBackup()) //File Copy will be made
{
this.backupCompleted += new
BackupCompletedEventHandler(onBackupCompleted);
Thread t = new Thread(new ThreadStart(makeBackup));
t.Start();
}
}
private void onBackupCompleted()
{
statusBar_audit.Panels[0].Text = "Done with backup"; /* I GET THE
ERROR HERE */
dataGrid_auditAddress.DataSource = null;

}
private void makeBackup()
{
File.Copy(_sFileName, _sFileName + ".bak");
onBackupCompleted();
}


Thanks for the help.
 
VMI said:
Im using a separate thread in my code to copy a huge file, but I get the
"Controls created on one thread cannot be parented to a control on a
<snip>

Don't mess with visual controls from your threads, they're not thread-safe.

Make a separate method to set your status panel text, and use the
Form.Invoke method to call it, Invoke will call the method on the main
GUI thread, ensuring that you won't have problems with threading in this
context.

ie. something like:

private delegate void SetStatusBarPanelDelegate(String newText);
private void SetStatusBarPanel(String newText)
{
statusBar_audit.Panels[0].Text = newText;
}

and in your onBackupCompleted:

Invoke(new SetStatusBarPanelDelegate(SetStatusBarPanel),
new Object[] { "Done with backup" });
 
Back
Top