Reputation: 5620
I am working on a stock market software (AmiBroker) plugin wherein I have to call a COM object in order to retrieve the active symbols. I.e. when user requests for a particular symbol I have to send a Request to the server to fetch the stock data. So, AmiBroker has exposed some functions using COM which allows to retrieve the symbols that have been requested.
Code
System.Timers.Timer tm = new Timer(1000);
tm.Elapsed += delagate(sender, e)
{
dynamic broker = Activator.CreateInstance(Type.GetTypeFromProgID("Broker.Application", true));
hashtable.Add(uniquernd, broker.GetActiveSymbols());
Marshal.ReleaseCOMObject(broker);
}
Note: This is how I've implemented the logic in C# (Don't find syntactical errors in this code)
Sometimes when I close the AmiBroker application every COM object gets disposed successfully. But sometimes it does stay in process which causes malfunctioning. Is there any alternate way to achieve this by ensuring that the object will get disposed every time?
Upvotes: 2
Views: 247
Reputation: 827
COM objects in C# need special handling.
You should use a variable to hold the pointer to each COM object, which means that if your object has a property that returns another COM object, you should use variables to keep them, and then use Marshal.ReleaseComObject(v);
on each.
Otherwise, the .NET framework will create an ah-hoc COM holder object, that will be freed some time in the future.
In your finally
clause, remember to set the variable to null, so that the Garbage Collector will free it completely.
You can also call GC.Collect();
to force it to collect garbage right now.
Upvotes: 2
Reputation: 910
The Marshal.FinalReleaseComObject
method will loop through all the references to the COM object provided and remove them. You might try that instead of ReleaseComObject().
Upvotes: 0