Update WinForm Controls from another thread _and_ class

后端 未结 2 1970
抹茶落季
抹茶落季 2020-12-06 08:31

I am making a WinForms program, which requires separate threads For readability and maintainability, i have separated all non-GUI code out into different classes. This class

相关标签:
2条回答
  • 2020-12-06 09:08

    It does not matter from which class you are updating the form. WinForm controls have to be updated on the same thread that they were created on.

    Hence, Control.Invoke, allows you to execute a method on the control on its own thread. This is also called asynchronous execution, since the call is actually queued up and executed separately.

    Look at this article from msdn, the example is similar to your example. A separate class on a separate thread updates a list box on the Form.

    ----- Update Here you do not have to pass this as a parameter.

    In your Winform class, have a public delegate that can update the controls.

    class WinForm : Form
    {
       public delegate void updateTextBoxDelegate(String textBoxString); // delegate type 
       public updateTextBoxDelegate updateTextBox; // delegate object
    
       void updateTextBox1(string str ) { textBox1.Text = str1; } // this method is invoked
    
       public WinForm()
       {
          ...
          updateTextBox = new updateTextBoxDelegate( updateTextBox1 ); // initialize delegate object
        ...
        Server serv = new Server();
    
    }
    

    From the ClientConnection Object, you do have to get a reference to the WinForm:Form object.

    class ClientConnection
    {
       ...
       void display( string strItem ) // can be called in a different thread from clientConnection object
       {
             Form1.Invoke( Form1.updateTextBox, strItem ); // updates textbox1 on winForm
       }
    }
    

    In the above case, 'this' is not passed.

    0 讨论(0)
  • 2020-12-06 09:31

    you can use backgroundworker to make your other thread, it allow you to deal easily with your GUI

    http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

    0 讨论(0)
提交回复
热议问题