Marshal.AddRefComObject anyone (take 2)? I had the chance to take at my original posting and realized that I did it incorrectly. Here is a modified example of how it might be used.
public class Test1 : IDispose { private SomeClass.Interop.IFoo m_pIFoo;
public void Test1() { m_pIFoo = (SomeClass.Interop.IFoo)new SomeClass.Interop.FooClass(); }
public SomeClass.Interop.IBar IBar { get {
// The following line of code increments the RCW count System.Runtime.InteropServices.Marshal.AddRefComObject(m_pIFoo);
return (SomeClass.Interop.IBar)m_pIFoo; } }
public void Dispose() { if (m_pIFoo != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_pIFoo); } }
public class Test2 : IDispose { private SomeClass.Interop.IBar m_pIBar; public void Test2() { Test1 test1 = new Test1(); m_pIBar = test1.IBar; // The following line of code decrements the RCW count to 1, leaving // m_pIBar valid! test1.Dispose(); } public void Dispose() { if (m_pIBar != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_pIBar); } }
Also, I do appreciate the feedback! I know that ref counting isn't the best solution, but I think it would work - especially if you think of Interop references as if they were file resources (i.e. you always clean them up deterministically).
10:13:56 AM
|