Thread and GUI

Hi,
My problem is: When the applications is started, I create a frame (with button and other components) in the principal thread. Later, i create an other Thread and i attempt to modify the frame in the second thread, but it doesn't work. I got this error message:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

How can I solve this problem
Thanks


Answer this question

Thread and GUI

  • jeffmorris

  • Maximilian Machedon

    You should never change controls from a different thread. I think it was finally forbidden in .NET 2.0.

    To change controls in a different thread you should use Invoke. There is a bunch of examples out there, one of which is this.

    HTH
    --mc


  • Al33327

    I don't know what you mean by frame but... I'll try and throw in my two cents.

    You need to call the beinginvoke on the form you wish to modify in the second thread. You'll need to create a delegate. Here is an example method that show you how to inline the code, this creates a typing affect which asychronously updates the UI. Anonymous methods make nice code. You can copy and paste this code.

     

    delegate void SomeDelegate(string t);  //The delegate definition

    public void ShowComplete(string Astring, System.Windows.Forms.Label mylabel)

    new Thread((ThreadStart)delegate() //Inline the delegate that is started by the thead.

    {

    SomeDelegate del = delegate(string t) //Inline a delegate that will be called to update the label

    {

    mylabel.Text += t;

    mylabel.Update();

    };

    foreach ( System.Char temp in Astring)

    {

    IAsyncResult res = this.BeginInvoke( del, temp.ToString()); //Call del ( the delegate we created above )

    res.AsyncWaitHandle.WaitOne(); // Wait till its done.

    Thread.Sleep(100); //Wait a tick and do the next char

    }

    Thread.Sleep(1000);

    this.BeginInvoke( (ThreadStart)delegate(){ mylabel.Text = ""; }); //Set the lable to "" after typing it out

    }).Start();

    }



  • Thread and GUI