Update GUI Control From Non-GUI-Thread Without Marshalling

In .Net when you want to update a GUI Control, for example a ListView, you have to execute your update code in the GUI Thread which controls your Form and its child GUI Objects. While you are in another Thread, you call the Invoke or BeginInvoke (for async.) method of your GUI Control for this purpose. You pass this method a delegate of your method, which contains your update code, and the GUI Thread invokes the method that is passed. Well the whole story is infact much more complicated and this article gives you a nice in-depth view on this topic:
WinForms UI Thread Invokes: An In-Depth Review of Invoke/BeginInvoke/InvokeRequred

 

This is how Microsoft wants us to manage our GUI stuff, everything in one Thread, to prevent cross-thread usage of GUI code and keep everything Thread-Safe. But this single-threaded architecture can cause the GUI to become unresponsive, if you need to do frequent updates. Now here is the thing, this problem can be easily bypassed by disabling the check, for the “illegal” attempt to run your update code in a Non-GUI-Thread, using the following line once while your form is loading:

 

[...]
private void theMainForm_Load(object sender, EventArgs e)
{
// Prevent the framework from checking what thread the GUI is updated from.
theMainForm.CheckForIllegalCrossThreadCalls = false;
[...]

Setting this property to false, the framework doesnt throw an exception anymore cause of a cross thread update. Now you are able to update a certain GUI Control from a thread, just dedicated for updating this control and as long as, only This dedicated thread updates (writes) the GUI Control, and others only read, everything still stays Threadsafe. This way, the GUI stays amazingly responsive because the GUI Thread isnt burdened with update tasks and a lot overhead is prevented.

 

Be careful using this trick, because if you let multiple threads update the Control simultaneously, the unsafe crossthread operations can cause some scary side effects and make it very difficult to debug your code.

 

Here an article, which covers this  approach with a perfect example:
An Alternate Way of Writing a Multithreaded GUI in C#

Leave a Reply

Your email address will not be published. Required fields are marked *