Thursday, August 25, 2016

SWT - Single UI threaded model

The backbone of any UI toolkits are threads. The most basic aspect of UI toolkits is to provide a nice event driven architecture, as events are the most integral part of any UI.
The underlying operating system maintains a queue of application events and if that event is long running and is blocked it will freeze your UI.
In SWT when a user presses a mouse a mouse pressed event is generated. Determining which window is supposed to receive the event and placing it in an event queue is done by the underlying OS.
SWT has a single UI thread which creates the display and from which all other widgets are created. When writing a SWT app the most common piece of code existing in all programs is
while (!shell.isDisposed())
if (!display.readAndDispatch())
display in SWT is the class which interacts with the underlying operating system. In the above code readAndDispatch() is the call which reads events from the event queue and dispatches them to the correct place.
Since there is only one UI thread, if we try and process events in the same thread the UI will freeze. This is where threads come to our rescue. But again when working with UI’s the most tricky and dangerous thing to do would be access UI components from non UI threads. If you spawn a new thread and try to update UI components from that non UI thread you will be in for a bummer. When your UI toolkit is SWT, it will nicely point out to you your chivalry and throw an SWTException.

No comments:

Post a Comment