-
Notifications
You must be signed in to change notification settings - Fork 1
Description
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).