Freeing Excel COM Objects

I have an Excel automation code that uses Excel COM objects. From other SO posts I know that the following can be done to free objects as early as possible:

Excel.Range rng = GetSomeRange();

// do something with rng...

Marshal.ReleaseComObject(rng);

      

However, if I iterate over the cells in the range, is the correct procedure performed?

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);

      

I'm not sure if I release each r

in rng

and then I also release rng

am, am I deleting twice, rng

or is it clearing up the additional links correctly r

before rng

and rng

?

Thank you Ambassador!

EDIT

I went for the last 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 reduced memory significantly ...

again thanks to everyone!

+3


source to share


1 answer


Unfortunately, there is a lot of false information circulating around. First, let me answer the answer clearly:

You don't need to call Marshal.ReleaseComObject

in most cases. What for? Because the garbage collector does it for you. * Note that I've said the most , you may find that retention of many links causes problems (for whatever reason). In cases where you decide to call Marshal.ReleaseComObject

.

Link :

Kristofer, we've always had automatic releases for COM objects as the GC determines to clean them up. They are not cleaned up immediately, but after some point after GC cleanup two. I have confirmed this with the team.

They said:

In the type of blog app it doesn't really matter, if people mess up their app, fail, and they end up with obvious link counting errors. In cases where their code is loaded inside the office and not the other way around, this is much more because you may end up freeing someone elses reference, then there may be problems that they don't notice in their code but break someone then elses office superstructure.

So the point is, while the ReleaseComObject is more deterministic, this is usually not necessary since the GC will do the same.



Also, I suggest you read Marshal.ReleaseComObject Considered Dangerous .

If you're tempted to call "Marshal.ReleaseComObject", can you be 100% sure that no other managed code still has access to the RCW? If the answer is no, then don't name it. The safest (and soundest) advice is to avoid the .ReleaseComObject marshal entirely on a system where components can be reused and versioned over time.

Now, there may be some reasons why you need to deallocate these COM objects deterministically, but in most cases, you can remove all of these calls Marshal.ReleaseComObject

.

+5


source







All Articles