Answer the question
In order to leave comments, you need to log in
How to properly release a COM object?
Good afternoon! How does Marshal.ReleaseComObject() work?
This is the object I'm using.
public class Object1C : IDisposable
{
private bool _disposed = false;
public Object1C(dynamic value)
{
Value = value;
}
public dynamic Value { get; private set; }
public Type Type => Value.GetType();
private void ReleaseUnmanagedResources()
{
if (_disposed) return;
Marshal.ReleaseComObject(Value);
_disposed = true;
}
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
~Object1C()
{
ReleaseUnmanagedResources();
}
}
public void Open()
{
Type comconnector = Type.GetTypeFromProgID("V83.COMConnector");
if(comconnector == null)
throw new Exception1c($"COM Class Object \"V83.COMConnector\" was not found or not registered in the system");
try
{
IV8COMConnector connectorInstance = (IV8COMConnector)Activator.CreateInstance(comconnector);
Object1C = new Object1C(connectorInstance.Connect(ConnectionArgs.ToString())); // Здесь создается объект
}
catch (Exception ex)
{
throw new Exception1c($"{ex.Message}\r\n{ConnectionArgs}");
}
}
static void Main(string[] args)
{
var connection = new Connection1C(new ConnectionArgs("srv", "erp", "Админ", ""));
connection.Open();
connection.Object1C.Dispose();
}
Answer the question
In order to leave comments, you need to log in
Marshal.ReleaseComObject()
must be called explicitly - in the same thread (thread) where we received this COM object.
The GC is running on a different thread. You can't call there. Therefore, the destructor will have to be removed.
I use the using construct - the code remains readable.
using (var conn = new Object1C(connectorInstance.Connect(ConnectionArgs.ToString())))
{
// Делаем необходимую работу
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question