Handling GUI Freezing in .NET Component Event Handlers


In .NET applications, GUI components must be accessed only from the main UI thread. Attempting to update the UI from within events fired by asynchronous components can cause the application to freeze.

IPWorks components can be broadly categorized based on their threading behavior. Components such as TCPClient, TCPServer, UDP, ICMP, MCast, XMPP, Telnet, MX, and DNS are non-blocking and asynchronous, while most other components are blocking and synchronous.

Blocking (synchronous) components are generally "plug-and-play" and can be used directly in GUI applications without additional handling. In contrast, non-blocking (asynchronous) components perform operations such as Connect, Send, and Disconnect on background threads and raise events like Connected, DataIn, and Disconnected upon completion.

Because these events are fired from worker threads, directly updating the GUI within them can lead to freezes or cross-thread issues. To address this, set the InvokeThrough property to a UI control (such as the main form), which ensures that event handlers are executed on the UI thread.

xmpp1.InvokeThrough = this;

Alternatively, InvokeThrough may be left unset and calls to the UI thread can be manually marshalled.

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.