I have some Excel automation code that uses Excel COM objects. From other SO posts I know that one should do the following to release objects at the earliest convenience:
Excel.Range rng = GetSomeRange();
// do something with rng...
Marshal.ReleaseComObject(rng);
However, if I loop through cells in a range, is the following the correct procedure?
Excel.Range rng = GetSomeRange();
foreach (Excel.Range r in rng)
{
// do something with r
Marshal.ReleaseComObject(r); // release at earliest possible convenience
}
Marshal.ReleaseComObject(rng);
What I'm unsure of here is that if I release each r in rng and then I also release rng am I effectively releasing rng twice or correctly releasing additional references r to rng and rng itself ?
Thanks in adv.!
EDIT
I went for the latter strategy:
Excel.Range rng = GetSomeRange();
foreach (Excel.Range r in rng)
{
// do something with r
Marshal.ReleaseComObject(r); // release at earliest possible convenience
}
Marshal.ReleaseComObject(rng);
which has reduced the memory significantly...
again - thanks to all!
r. See this answer stackoverflow.com/a/159419/141172