.Net components hang when accessing GUI from events

In .Net, GUI components have to be accessed only from the GUI thread. If you try updating GUI components while inside an event of an asynchronous component, the application could freeze.' pubdate='02/05/2014' > IPWorks components fall in two categories in respect to threading behavior. Such separation is dictated from performance and the nature of the implemented protocol. IPPort, IPDaemon, UDPPort, ICMPPort, MCast, XMPP, Telnet, MX, DNS are non blocking and asynchronous, the rest of the components are blocking and synchronous.

The blocking/synchronous components are "plug and play" in the sense that there is absolutely no need to implement any extra plumbing to have them work even inside GUI applications.

The non blocking/asynchronous components require extra plumbing when used inside GUI applications due to the .NET limitation that "GUI components have to be accessed only from the GUI thread".

You connect, send data, and disconnect in a non-blocking asynchronous manner by using methods such as Connect, Send, and Disconnect.

There are respective events such as Connected, DataIn, and Disconnected that inform you in a later stage about the operation result. Your method calls only "ask" the component to perform the task and the control is immediately returned to the calling thread whereas the corresponding events are generated and fired from worker threads inside the component. If you try updating GUI components while inside the event, the application could simply freeze.

Simply set the InvokeThrough property of the component to the instance of the form, and the component will take care of this problem for you by automatically invoking onto the main thread, ie:

xmpp1.InvokeThrough = this;

Alternatively you could leave InvokeThrough to its default (null) and either not access the GUI from the event or do the invoking yourself.

---

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