Last week I talked about using CoInitializeSecurity() in order to access the Virtual Server COM APIs from a managed application (.Net). The next thing you need to be aware of wehn developing a managed application that controls Virtual Server is apartment threading models.
At a very high level an apartment is a logical container inside an application for COM objects which share the same thread access rules (i.e., regulations governing how the methods and properties of an object are invoked from threads within and without the apartment in which the object belongs). The most common Thread Apartment model is the ‘Single Threaded Apartment’ (STA) model – and this is the default for new .Net applications.
Virtual Server – however – requires that you use a ‘Multi Threaded Apartment’ (MTA) model. The reason for this is that there are significant potential performance issues when accessing the Virtual Server COM APIs from a STA model application. There are two ways that you can use the MTA model:
- Turn your entire application into a MTA model application by using the following adornment on a shared sub main routine:
Shared Sub Main()
- Keep your application as a STA model application – but launch any COM actions on a separate thread with a MTA model:
Dim initVSStuff As New vsStuff
Dim aThread As Thread
‘Start vsStuff class on a separate thread with a MTA model
aThread = New Thread(AddressOf initVSStuff.Init)
aThread.ApartmentState = ApartmentState.MTA
‘Wait for the thread to complete
Do Until aThread.ThreadState = ThreadState.Stopped
Application.DoEvents() : Thread.Sleep(10)
While option (1) is obviously easier – option (2) gives you the flexibility of mixing components that require STA and MTA models (for example – the VMRC ActiveX control will only run on a STA modeled thread). A third option would be to have your main application run as a MTA model application and then launch STA model threads when needed.