Update WinForm Controls from another thread _and_

2020-02-01 02:37发布

问题:

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 also 'generates' another class, which does some processing. However, i have now run into the issue where i need to change a WinForms control (append a string to textbox) from a thread that was initiated in a different class

I have searched around, and found solutions for different threads, and in different classes, but not both and the solutions provided seem incompatible (to me)

This may be the biggest 'lead' however: How to update UI from another thread running in another class

Class Hierarchy example:

class WinForm : Form
{
    ...
    Server serv = new Server();
}

// Server is in a different thread to winform
class Server
{
    ...
    ClientConnection = new ClientConnection();
}

// Another new thread is created to run this class
class ClientConnection
{
    //Want to modify winform from here
}

I understand that eventhandlers are probably the way to go, but i can't work out how to do so in this situation (I am also open to other suggestions ;) )

Any help appreciated

回答1:

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.



回答2:

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