June 17, 2003

C# / COM interop and scarce resources

Recently, I had to write some C# code to call a specialized device driver. The driver manufacturer had supplied a COM object that support dual interfaces, complete with Typelib. So calling it from C# was easy -- add a reference to the COM object from your C# project file in Visual Studio .NET, and start using it. C# does a really good job with interoperability with COM. The typelib importer even converts COM 'connection points' (which never completely made sense to me) into .NET events (which make perfect sense to me).

The problem I was having had to do with releasing the COM object. Normally, in C#, you don't ever worry about releasing anything -- eventually, the garbage collector will run, and things will magically disappear. Microsoft has done a lot of work on the performance of .NET and the garbage collector in particular, so I've never really noticed the performance hit from this. However, one of the COM objects I received from the driver represented a scarce resource. For a driver, this is fairly common -- drivers have to hand out pointers to hardware resources all the time (for example, video card memory, which is often pretty limited). I couldn't wait for the garbage collector to run; by the time it did, the driver would have completely run out of the scarce resource.

Someone else at Microsoft on the .NET team finally pointed me to the obvious answer -- Marshal.ReleaseComObject does the trick. Despite the name, this isn't quite the same as just calling IUnknown->Release() on an object, because of the way the CLR handles ref counting of COM objects. For (lots) more information, check out this blog entry from a .NET engineer.

Posted by Mike at June 17, 2003 11:42 PM