Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB6,MTS,COM+
Expertise: Intermediate
Dec 8, 2001

Never use New to create MTS/COM+ objects

A common question among VB developers is: Why is it dangerous the use of the New keyword in VB to create COM objects registered under MTS/COM+?

The New keyword is the only way to go when you want to create objects that are defined as PublicNotCreatable or Private (CreateObject doesn't work) inside the same component as the calling code. As you know VB lets you use New to create Multiuse classes as well. Unfortunately the New keyword has a couple of drawbacks:

1) In situations where the caller and the callee are in the same EXE/DLL COM component VB perform an internal creation of the COM object bypassing the COM run-time (and the MTS run-time if the object is registered under MTS). While this fact is not a problem under a non-MTS environment, the situation gets very dangerous under MTS and COM+. What happens is that, since MTS/COM+ is not notified of the object creation, the newly created object gets access to the ObjectContext of the father and MTS sees the code running inside method calls of the child object as "inline-code" of the father. I leave as an exercise to the reader what can happen if the child object calls SetComplete (against the ObjectContext of the father).

2) When you declare an object (Interface) with the syntax


Dim x As New MyClass
VB checks every time the object is referenced in the code. If it is Nothing, VB silently (re)creates it (This means you'll never get a "object variable or with block not set" error). If you are not aware of this your code could follow unexpected execution paths.


Public sub DoWork()      
  Dim X as New MyClass   ' MyClass is registered as "requires transaction"
  x.dosomemorework       ' VB creates it, the component ball start spinning in 
                         ' the MTS explorer, the transaction start
  Set x = Nothing        ' The ball stop spinning
  If x Is Nothing Then   ' VB recreates it, the ball start spinning again, the 
                         ' transaction start again
      Format Drive C     '  this code will never be executed
  End If     
  ' From here to when x goes out of scope x is activated 
  ' (and probably you don't know this).  
End Sub    
This tip is taken from the FAQ list that Enrico mantains at his own home page (www.sabbasoft.com/mts_faq.htm).
Enrico Sabbadin
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap