How to free the COM object which holds references to resources in a timely manner?
In managed code, if application is executing RCW and we release RCW at that time then it will encounter errors so releasing objects activities should be done with proper care.
This code is simple to use and understand. I hope it will be useful for you.
Purpose:
Object is passed as a parameter in the method so that it will be released whenever it is no longer in use.
The ReleaseComObject method decrements the reference count of an RCW.
GC.Collect method is used to force garbage collection.
If there is any error then messagebox is used to show that error.
Version support:
This method can be used for .Net framework versions 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}