By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,290 Members | 1,195 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,290 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.
Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
VMI wrote:
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" });

--
Lasse Vågsæther Karlsen
http://www.vkarlsen.no/
mailto:la***@vkarlsen.no
PGP KeyID: 0x0270466B
Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.