Hi Netters,

I am doing a bit of work with COM interface references and am slowly but
surely learning the ins and outs of interop.

One thing that bothers me about COM interop is that most COM servers expect
deterministic finalization. COM objects that are only expected to be used
for a short period of time should be cleaned up quickly.

Dotnet of course only has nondeterministic finalization for heap objects.
The disposable pattern is the common way to control the life time of system
resources. Unfortunately the COM Runtime Callable Wrapper does not implement
the IDisposable interface and does not support this pattern directly.

So I made a wrapper object that implements IDisposable and then calls
Marshal.ReleaseComObject(...) on Dispose(). This class works in a similar
way to the WeakReference class. There is no finalizer because the RCW knows
how to finalize itself.

Any comments, suggestions, or brickbats are welcome.

I have also implemented an IClassFactory and will post the code when I get a
chance.

--
Peter

=======>
public class ComObject : IDisposable
{
        private Object _obj;

        // Constructor
        public ComObject(Object obj)
        {
                if(obj == null) throw new
                        ArgumentNullException("obj");
                _obj = obj;
        }

        // Properties
        public Object Target
        {
                get { return _obj; }
                set
                {
                        lock(this)
                        _obj = value;
                }
        }

        // Implement IDisposable interface
        public void Dispose()
        {
                Dispose(true);
                // We don't have a finalizer, so
                // don't worry about Suppressing the
                // finalizer
        }

        // Implementation
        private void Dispose(Boolean disposing)
        {
                // Only allow releasing once!
                Object obj;
                lock(this)
                {
                        obj = _obj;
                        _obj = null;
                }

                if(obj != null)
                        Marshal.ReleaseComObject(obj);
        }
}
<=======

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to