Proper disposal of COM interop objects in C# parti

2019-02-06 05:56发布

问题:

I am developing an application that relies heavily on multiple Microsoft Office products including Access, Excel, Word, PowerPoint and Outlook among others. While doing research on interop I found out that starting with VS2010 and .NET 4, we thankfully no longer have to go through the nightmares of PIAs.

Furthermore, I have been reading a lot of articles on proper disposal of objects, the most sensible one seemed to be this one.

However, the article is 5 years old and there are not many authoritative publications on the subject AFAIK. Here is a sample of code from the above link:

' Cleanup:
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()

Marshal.FinalReleaseComObject(worksheet)

oWB.Close(SaveChanges:=False)
Marshal.FinalReleaseComObject(workbook)

oApp.Quit()
Marshal.FinalReleaseComObject(application)

What I want to know is by today's standards, how accurate is this and what should I look out for if I expect to support my application for the coming few years?

UPDATE: A link to some credible articles would be highly appreciated. By the way, this is not a server side application. This will be running in computer labs where we have users interact with office products that we instantiate for them.

FOUND IT: This three-part article is probably the closest to an authoritative account I would expect to find.

回答1:

Depending on the version of Office you are controlling through interop, and the circumstances that occur on the server, yes, you may need to do some serious convolutions to get rid of a running instance of one of the Office applications. There are unpredictable (and unnecessary) dialogs which, for example, Word will open when it is not interactive (None of the Office applications are particularly well designed for unattended execution, thus the recommendation that even with the latest versions that they not be installed for server-side use).

For server cases, consider using Aspose's stack rather than Office, or another of the alternatives. The interactive, local use cases, you may need that "extra vigorous killing" on occasion since the Office automation servers are particularly badly behaved unmanaged objects.



回答2:

Objects should be disposed automatically by the GC after the object goes out of scope. If you need to release them sooner, you can use Marshal.ReleaseComObject http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx



回答3:

If you want to release COM objects fully especially in MS Office COM Objects, its very highly recommended that you release sub objects that you must have used which are inside the parent objects.

In your example, I would say release all Cell, Range any other objects that you may have used before releasing the worksheet that the cell, range or any other object belongs to.