Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to release the COM object on every 'foreach' iteration?

Here's the (potential) problem:

I create a COM object, and then use a 'foreach' to iterate through each element in a collection it returns. Do I need to release each individual element I iterate through in the collection? (See code below.) If so, I can't think of a way to effectively to release it from within a 'finally' statement, just in case there is an error as the item is being operated upon.

Any suggestions?

private static void doStuff()
{
    ComObjectClass manager = null;

    try
    {
        manager = new ComObjectClass();
        foreach (ComObject item in manager.GetCollectionOfItems())
        {
            Log.Debug(item.Name);
            releaseComObject(item); // <-- Do I need this line?
                                    //     It isn't in a 'finally' block...
                                    //             ...Possible memory leak?
        }
    }
    catch (Exception) { }
    finally
    {
        releaseComObject(manager);
    }
}

private static void releaseComObject(object instance)
{
    if (instance != null)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(instance);
        }
        catch
        {
            /* log potential memory leak */
            Log.Debug("Potential memory leak: Unable to release COM object.");
        }
        finally
        {
            instance = null;
        }
    }
}
like image 975
Matt Avatar asked Nov 30 '10 19:11

Matt


1 Answers

You should not use a foreach statement with a COM object, as a reference is made behind the scenes to which you have no control over releasing. I would switch to a for loop and make sure you never use two dots with COM objects.

The way this would look would be:

try
{
    manager = new ComObjectClass();
    ComObject comObject = null;
    ComObject[] collectionOfComItems = manager.GetCollectionOfItems();
    try
    {
        for(int i = 0; i < collectionOfComItems.Count; i++)
        {
            comObject = collectionOfComItems[i];
            ReleaseComObject(comObject);
        }
    }            
    finally
    {
        ReleaseComObject(comObject);
    }
}
finally 
{
    ReleaseComObject(manager);
}
like image 105
Mark Avenius Avatar answered Oct 23 '22 19:10

Mark Avenius