I have a COM object implemented in C# (see below). It owns some IDisposable
resource. Where should I dispose that resource?
Looks like finalizer is never called and I cannot overload IUnknown::Release
method.
[ComVisible(true)]
[Guid("1992EC2F-087A-4264-B5B2-5E2E757F1A75")]
public class ComServer
{
IDisposable disposableResource; //where to dispose IDisposable resource?
public ComServer()
{
disposableResource = File.Open(@"c:\somefile.txt", FileMode.OpenOrCreate);
Console.WriteLine("ComServer.ComServer");
}
~ComServer() //finalizer is never called!
{
disposableResource.Dispose();
Console.WriteLine("ComServer.~ComServer");
}
}
Edited: the COM server is used in a native third party application, it's impossible to call Dispose
on client side or make any changes there.
Release()
, you'd never see the ref-count go to zero. Your clients will need to callDispose()
explicitly. – Peter DunihoDispose()
orClose()
method then you can just put the method there. Otherwise, you'll want to have clients query forIDisposable
and get theDispose()
method from there. This is explained in more detail in those other two questions. – Peter Duniho