开发者

Proper Interop Cleanup

I have the below method for spellchecking in my in house app. As a new programmer this was pieced together through multiple sources and tweaked until it worked for me.

As I grow and learn I come across things that make me go, hmm. Like this SO post,How to properly clean up Excel interop objects in C#, that talks about proper Interop cleanup.

I noticed it mentions repeatedly the use of Marshal.FinalReleaseComObject() or Marshal.ReleaseComObject().

My question is this, based on the code below do I need this as well? Thanks

        public string CheckSpelling(string text)
    {
        Word.Application app = new Word.Application();
        object nullobj = Missing.Value;
        object template = Missing.Value;
        object newTemplate = Missing.Value;
        object documentType = Missing.Value;
        object visible = false;
        object optional = Missing.Value;
        object savechanges = false;
        app.ShowMe();

        Word._Document doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);

        doc.Words.First.InsertBefore(text);
        Word.ProofreadingErrors errors = doc.SpellingErrors;

        var ecount = errors.Count;
        doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional, 
            ref optional, ref optional, ref optional, ref optional, ref optional, 
            ref optional, ref optional, ref optional);
        object first = 0;
        object last = doc.Characters.Count - 1;
        开发者_运维问答var results = doc.Range(ref first, ref last).Text;
        doc.Close(ref savechanges, ref nullobj, ref nullobj);
        app.Quit(ref savechanges, ref nullobj, ref nullobj);

        return results;
    }


I would say definitely. You should always use Marshal.ReleaseComObject to clean up unmanaged COM references in .NET code.


You also should explicitly create and release intermediate objects. In the case of Word._Document doc = app.Documents.Add(...);, you are implicitly creating a _Documents object that needs to be released. You should break it into two lines:

Word._Documents docs = app.Documents;
Word._Document doc = docs.Add(...);
// release docs and doc after use

It's often called the two dots rule. Anytime that there are two dots in COM interop code, you probably need to break it out, so the same rule would apply to doc.Words.First.InsertBefore(text); line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜