Skip to content

Fix COM object managment #5

@dhoepelman

Description

@dhoepelman

COM objects used from a .NET environment are not managed like you expect other types to be. They must be manually managed, primarily the most important thing is to release every COM object acquired with Marshal.ReleaseComObject
The excel interop Bumblebee uses heavily relies on .NET objects.

This is incredibly annoying, take for example the following very common use case:

var range = excel.GetSomeRange();
foreach(var cell in range) {
    doSomethingWith(cell);
}

This leaks range, all cells and the iterator.
Correct code is:

Range range = null;
IEnumerator<Range> cellIterator = null;
try {
    range = excel.GetSomeRange();
    cellIterator = range.GetEnumerator();
    while(cellIterator.MoveNext()) {
        Range cell = null;
        try {
            cell = cellIterator.Current;
            doSomethingWith(cell);
        }
        finally {
            if(cell != null) Marshal.ReleaseComObject(cell);
        }
    }
}
finally {
    if(cellIterator != null) Marshal.ReleaseComObject(cellIterator);
    if(range != null) Marshal.ReleaseComObject(range);
}

With LINQ this gets even more annoying, as you cannot use simple lambdas anymore.

The easiest way to fix this probably is to port it to use NetOffice instead of excel interop directly, because this library provides a (managed) wrapper around the COM objects.
This library also cleans up several idiosyncrasies in the API and is version independent (i.e. is works with every Excel version).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions