Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Beware of global variables in Visual Basic COM objects

0.00/5 (No votes)
17 Feb 2000 1  
A note for C++ programmers about global varaibles in Apartment threaded VB COM objects

I am primarily a C++ developer that was formally introduced to Visual Basic over a year ago. Being on the Toolkit team for my company's product, all of the toolkit COM objects I develop are implemented using ATL + STL. All the same, I have become very proficient in Visual Basic and use it for developing test beds or sample COM objects that implement our base interfaces.

A couple of Microsoft Web Development and eCommerce seminars that I have attended in the past year had many of the speakers preaching that business logic should be ideally implemented in COM objects instead of scripting. Of course, VB is the tool of choice if the script programmers in question do not have any C++ / COM development background.

Even though using global variables is not always a programmers first choice, I have seen a lot of code that relies on it. If you do not use global variables in your code, then you can safely skip the rest of the article. I myself go to great lengths to ensure that I avoid using global variables but sometimes they are inevitable.

For C++ COM objects, a global variable is shared by all instances of the COM objects, irrespective of which apartment they are created in or which thread they are accessed by. If a C++ COM object is Apartment, Both or Free threaded, all global variables need to be protected with a Critical Section.

Visual Basic allows creating COM objects that are either Single or Apartment threaded. In the former case, all instances of the object are going to be created in the Main STA. So there is no problem with using global variables in this situation because all objects will only be accessed by the one thread associated with that apartment. In the latter case, Visual Basic uses thread local storage (TLS) to store instances of global variables instead of wrapping them up with a critical section. So the result is that there is one instance of any global variable per thread.

If this is what you expected then well and good. If you are like me and come from a C++ / COM background, then this comes as a surprise. It can also cause problems with the application logic. If you think that you are never going to encounter these threading issues, think again. If you are developing web applications, ASP by default uses a thread pool of 10 threads per processor.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here