Marshal User Interface Code to the Correct Thread

Problem

You need to update a user interface element on a window from another thread.

Solution

Place your update logic in a separate subroutine, and use the Control.Invoke method to marshal this code to the user interface thread.

Discussion

Windows controls are not thread-safe. That means that it isn’t safe to update a user interface control from any thread other than the thread that created it. In fact, you might test code that ignores this restriction without experiencing any trouble, only to have the same code cause maddeningly elusive problems in a production environment.

This problem isn’t restricted to code that executes in a custom-threaded object. It also applies to code that responds to a callback ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.