Call Dispose on your ServicedComponent’s (please)

My last blog entry pointed at a Enterprise Services FAQ which mentions that you should
call .Dispose on your ServicedComponent proxies.

Now this “recommendation” isn’t documented very well, hence most people don’t do it
and you won’t hit problems most of the time, however I did come across the following
side-affect if you don’t call Dispose recently.

Each ServicedComponentProxy has an associated COM+ context which is basically an OS
handle and some memory, if you don’t call .Dispose on your proxy this resource will
not get cleaned up until the GC runs later as with most things in the .NET framework.

The ServicedComponentProxy implements a Finalizer which means it won’t really get
cleaned up until the second time the GC runs (see the GC article below for why), this
could mean that the COM+ context won’t get cleaned up for a while.  Fortunately
the ServicedComponentProxy implements IDisposable which allows you to force the component
to free up the memory straight away by calling Dispose().

Now all of this isn’t an issue normally, but if your relying on the Finalizer to free
up your memory and your rapidly creating, using, and destroying ServicedComponents
the single finalization thread can get behind on servicing the finalization queue
and your application may look like it’s leaking (it will eventually however release
the memory once the finalizer thread catches up with the work).

Therefore in high stress envrionments it’s recommended that you
call Dispose, and indeed you should really be calling Dispose everywhere as the FAQ
says – there may well be other side-effects caused by not calling Dispose.

Garbage Collection: Automatic Memory Management in the Microsoft
.NET Framework

Enterprise Services (COM+) in .NET

Comments (3)

  1. Chanian, Raj says:

    IDisposable Pattern vs Need for Finalize

  2. Coleman says:

    Looking at the source via Reflector, it looks like the Dispose method is called during the internal_Deactivate method.  In a JITed component, isn’t this always the case especially if you decorate all public methods with [AutoComplete] ?  Isn’t Deactivate always called?

    Additionally, how does this work with DCOM?  Does it make another network hop in order to call the Dispose method on the remote component?