Visual Basic Concepts
Scalability and Multithreading
When a component has one thread of execution, code for only one object can execute at any given time. The Automation feature of the Component Object Model (COM) deals with this situation by serializing requests. That is, the requests are queued and processed one at a time until all have been completed.
In a multithreading operating environment, serialization protects single-threaded objects from overlapping client requests — that is, from code in a property or method being executed while one or more previous client requests are still being executed. Overlapping requests can cause internal data errors if objects aren't designed for reentrancy, as discussed in "Apartment-Model Threading in Visual Basic."
Serialization is thus an extremely important feature of Automation. However, serialization of single-threaded components means that requests are sometimes blocked. For example, suppose you're using a Widget object that has two methods:
The Spin method takes anywhere from several seconds to half an hour.
The Flip method is almost instantaneous.
Because 32-bit applications are preemptively multitasked, a second application could call the Flip method while the Spin method is already running. As shown in Figure 8.2, the short Flip method is blocked until the long Spin method is complete.
Figure 8.2 Blocking in a component with MultiUse objects
When short operations are blocked by long ones, productivity suffers and user frustration rises. Components that behave in this fashion are said to scale poorly. That is, they work poorly if many requests of mixed length are made.
Visual Basic has two component features for avoiding blocked calls — multithreading and SingleUse objects. These features are described in the following topics:
Apartment-Model Threading in Visual Basic To use threads effectively, it’s important to understand Visual Basic’s use of ActiveX apartment-model threading and its implications for global data.
Designing Thread-Safe DLLs Making in-process components safe for use with multithreaded clients.
Designing Multithreaded Out-of-Process Components Explains the three models available for assigning objects to threads.
Using Multiple Threads of Execution Introducing multithreading on a single-processor machine is not necessarily a blessing.
Event Logging for Multithreaded Components Your component can log suppressed message box and error dialog text to the system event log or to a log file.
Debugging Limitations for Multithreaded Components Describes the limitations of the development environment.
Scalability Through Multiple Processes: SingleUse Objects Visual Basic provides a second means of ensuring one thread per object, for cases where your component must show forms.