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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • VMI

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

    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 BackupCompleted EventHandler();
    private event BackupCompleted EventHandler backupCompleted ;
    private void btn_run_click(o bject sender, System.EventArg s e)
    {
    if (myMsgs.createB ackup()) //File Copy will be made
    {
    this.backupComp leted += new
    BackupCompleted EventHandler(on BackupCompleted );
    Thread t = new Thread(new ThreadStart(mak eBackup));
    t.Start();
    }
    }
    private void onBackupComplet ed()
    {
    statusBar_audit .Panels[0].Text = "Done with backup"; /* I GET THE
    ERROR HERE */
    dataGrid_auditA ddress.DataSour ce = null;

    }
    private void makeBackup()
    {
    File.Copy(_sFil eName, _sFileName + ".bak");
    onBackupComplet ed();
    }


    Thanks for the help.


  • Lasse Vågsæther Karlsen

    #2
    Re: Threading question "Contro ls created on one thread cannot beparented to a control on a different thread."

    VMI wrote:[color=blue]
    > 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[/color]
    <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 SetStatusBarPan elDelegate(Stri ng newText);
    private void SetStatusBarPan el(String newText)
    {
    statusBar_audit .Panels[0].Text = newText;
    }

    and in your onBackupComplet ed:

    Invoke(new SetStatusBarPan elDelegate(SetS tatusBarPanel),
    new Object[] { "Done with backup" });

    --
    Lasse Vågsæther Karlsen

    mailto:lasse@vk arlsen.no
    PGP KeyID: 0x0270466B

    Comment

    Working...