Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't COM object use IDisposable?

Tags:

.net

com

Why don't COM object use IDisposable in their CLR Callable Wrappers?

like image 263
Jonathan Allen Avatar asked Sep 19 '11 07:09

Jonathan Allen


People also ask

Why do we use IDisposable in C#?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.

What happens if you dont dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

What is the purpose of IDisposable?

IDisposable interface is to release unmanaged resources. This framework would detect that an object is no longer needed as soon as it occurs and automatically free up the memory.

When should a class implement IDisposable?

If you access unmanaged resources (e.g. files, database connections etc.) in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed.


1 Answers

Presumably such an IDisposable implementation would call Marshal.ReleaseComObject.

There are cases where calling Marshal.ReleaseComObject is a good idea, for example to get an Office application to quit after automation from a .NET client.

But as the documentation for Marshal.ReleaseComObject states, it should not be used in the general case - and probably not at all for in-proc COM objects. Here's a blog post with some more detailed info.

Hence it would not have been a good idea to encourage people to use it by calling it from an IDisposable implementation in the RCW.

However, what's interesting is that the Silverlight 4 AutomationFactory.CreateObject method does return a dynamic object that is IDisposable. And tests seem to show that this does in fact release the COM reference, though documentation is a bit sparse.

like image 156
Joe Avatar answered Sep 19 '22 22:09

Joe