简体   繁体   中英

C#: Freeing memory from Interop.Visio COM objects

I'm automating drawings in Visio using C#. I'm using Microsoft.Office.Interop.Visio. When I automate a drawing, I'm creating 7 Shape objects.When the drawing is completed and function is done, I've noticed in the diagnostics that memory usage keeps going up. It starts out at 16MB, and for every 2 times I run click the button to create a drawing, memory goes up 1MB.

The only method that stopped this from happening is using GC.Collect(). But from all my reading, everyone says not to use it. So what is the proper way to close a COM object then? I read also that this might be one of the rare instances that GC.Collect is ok to use, but not sure.

The proper way is to use Marshal.ReleaseComObject whenever you have finished using a COM object.

Yes GC.Collect will work like 90% of the time assuming you don't use a ton of COM objects. But since COM object is a native resource and GC can't determine the life cycle of those very well compared to managed resources.

Microsoft has an article suggesting that with very low chances GC will actually run into race condition and cause memory corruption (I have seen this many times, the end result is AccessViolation exception or .NET stack corruption)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM