C# – Update GUI from Another Thread and Class in Windows Forms Application

.netc++multithreadingwinforms

I've searched a ton, but I can't seem find anything relating to my specific problem.

I want to be able to update my MainUI form from another class (SocketListener) and within that I have a thread that handles the networking (clientThread). Right now I can run simple outputs from the networking thread such as writing to the debugger output and creating a MessageBox.

But what I really want to do is be able to invoke code from the clientThread that will do things on my MainUI instance. How can I do this?

Also, if anyone wants specific portions of the code then I can post it to help give you a better understanding of what I'm asking.

Best regards!

Best Answer

Check the InvokeRequired of the Control class, and if it's true, then call the Invoke and pass in a delegate (usually an anonymous method) that does what you want to do on the client's thread.

Example:

public void DoWork(Form form)
{
    if (form.InvokeRequired)
    {
        // We're on a thread other than the GUI thread
        form.Invoke(new MethodInvoker(() => DoWork(form)));
        return;
    }

    // Do what you need to do to the form here
    form.Text = "Foo";
}