C# / .Net WinForms GUI Thread Invoke solution

In .Net WinForms (and WPF for that matter) only the main GUI thread is allowed to make any change to GUI. If you attempt to do so from another thread then Visual Studio MDA will let you know that you made a mistake. This is actually an improvement from VS2003 where nobody said anything, so your application would mysteriously hang every so often.

But still its a pain in the neck to keep jumping between threads all the time. Often you want multiple threads running and updating the form whenever they see fit.

So… I ran Reflector on .Net 4.0 WinForm Form, copied source, then wrote up a small PERL script to create the majority of what you see below.

Basically this is a partial Form class that hides most normal Form methods and replaces them with new ones that automatically invoke GUI thread if required.

It’s a quick hack, but it works… The heart of the whole operation is GUIInvokeMethod(). If you don’t want all the hiding then this could be useful to keep in your form.

You can create similar methods like this for your user control.

The important part:

The whole file:

 

3 thoughts on “C# / .Net WinForms GUI Thread Invoke solution”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Tedds blog

Subscribe now to keep reading and get access to the full archive.

Continue reading