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
Best Answer
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.
From the ClientConnection Object, you do have to get a reference to the WinForm:Form object.
In the above case, 'this' is not passed.