Apartment-Model Threading


With Visual Basic 5 comes the ability to build thread-safe ActiveX DLLs and out-of-process servers. There is one condition on any Visual Basic application before it can be multi-threaded - it has to need no user interaction. If the Visual Basic application has any user-interface, it is limited to being a regular old single-threaded Visual Basic application. If there is no user interaction involved, you can enable multi-threaded operation by selecting Unattended Execution on the project properties, as shown in Figure 23.6.

Figure 23.6

Setting Unattended Execution on a Visual Basic project, allows it to accommodate multiple threads of execution.

Selecting Unattended Execution suppresses all forms of user interaction, including message boxes and system error messages. These messages are redirected to either a message log or the system event log, if running on Windows NT.

Microsoft simplified memory object management and thread synchronization when it made the decision to add threading capabilities to Visual Basic. Microsoft decided to implement something called apartment-model threading. With apartment-model threading, every thread is given its own individual copies of every memory object and variable that is used and accessed by the thread, as shown in Figure 23.7. In a sense, each thread is given its own apartment with everything the thread needs placed in the apartment, and the thread is forced to stay in its apartment. While this frees you, as the programmer, from having to worry about coordinating access to variables and resources between threads, it also limits what you can do. While it’s not impossible, the apartment-model makes it very difficult to perform any cross-thread communication, and it involves an inordinately large amount of overhead, effectively discouraging any real cross-thread communications or resource sharing.

Figure 23.7

Apartment-model threading with a Widget object class makes complete copies of the object for each thread.