Can I reference / use COM objects in my finalizer?

I have a COM type (created using tlbimp.exe ) and a C # class that wraps this object. I want to do some cleanup in the finalizer for my C # shell. Following the recommendations here , I could write something like this:

public class MyClass : IDisposable { private IMyComObject comObject; public MyClass() { comObject = new MyComObject(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~MyClass() { Dispose(false); } protected virtual void Dispose(bool disposing) { // Be tollerant of partially constructed instances if (comObject != null) { comObject.Cleanup(); // Account for object being disposed twice comObject = null; } } // Other bits go here... } 

I know that finalizers can be executed in any order, so I should not try to use any object that the finalizer implements, however as far as I can tell, the created COM types created by tlbimp do not implement the finalizer, and therefore there should be higher OK

I could not find any official documentation about this, so my question is is it safe to reference and use COM objects in the finalizer?

+4
source share
1 answer

I created an abstract com shell class from which I inferred all com shell classes. I work very well. My source code is VB since I need late binding. The rest of the application is written in C #.

 public abstract class ComWrapper : IDisposable { protected internal object _comObject; protected ComWrapper(object comObject) { _comObject = comObject; } #region " IDisposable Support " private bool _disposed = false; protected virtual void FreeManagedObjects() { } protected virtual void FreeUnmanagedObjects() { ReleaseComObject(_comObject); } private void Dispose(bool disposing) { if (!_disposed) { if (disposing) { FreeManagedObjects(); } FreeUnmanagedObjects(); _disposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected override void Finalize() { Dispose(false); base.Finalize(); } #endregion } 

and

 public static class Helpers { public static void ReleaseComObject(ref object o) { if ((o != null)) { try { Marshal.ReleaseComObject(o); } catch { } finally { o = null; } } } public static string ToDotNetString(object comString) { if (comString == null) { return string.Empty; } string s = comString.ToString(); ReleaseComObject(ref comString); return s; } } 
-1
source

Source: https://habr.com/ru/post/1380195/


All Articles