我的应用程序中的Winword.exe有多近

时间:2012-04-25 13:16:36

标签: c# ms-word

  1. 当我启动我的应用程序并打开word文件时,我在taskmanager中看到3个进程winword.exe 在我调用'close'后,函数1进程winword.exe关闭。

  2. 当我在析构函数中调用worddoc.close()或wordapp.quit()时,我得到了异常“已经与其底层RCW分离的COM对象无法使用。”

  3. public class WordHelper
    {
        private object nullobj = System.Reflection.Missing.Value;
    
        public string context = "";
    
        Microsoft.Office.Interop.Word.Document doc = new Document();
        Microsoft.Office.Interop.Word.Application wordApp = new Application();
    
        public WordHelper(string FileName)
        {
               //Open word file
        }
    
        //somefunction fo work with file
    
        public void CloseWord()
        {
            doc.Close();
            wordApp.Quit();
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wordApp);
        }
    
        ~WordHelper()
        {
            //i got exception
            doc.Close();
            wordApp.Quit();
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wordApp);
        }
    }
    

    我如何称呼我的班级

            WordHelper wddoc = new WordHelper("C:\\Test Word\\Test.docx");
            wddoc.CloseWord(); //this line i use and can close 1 process not 3
            //One process close after i close application
    

    最后我要关闭我的应用程序打开的所有winword.exe,我想在析构函数中关闭它们。最后,我需要关闭由我的应用程序打开的所有'winword.exe',我需要在析构函数中关闭它们。

2 个答案:

答案 0 :(得分:4)

您在终结器(different than a destructor)中执行此操作。终结者是非确定性的,这意味着当他们运行时,成员可能已经最终确定,因此不再有效。

我将实现Dispose pattern并显式控制单词COM对象的生命周期。 This answer有很多可以帮到你的好链接。

答案 1 :(得分:-2)

//找出WINWORD.exe进程并将RealTime Priority设置为WINWORD.exe //这用于快速处理

Process[] proces = Process.GetProcessesByName("WINWORD");


foreach (Process proc in proces)

{

   proc.PriorityClass = ProcessPriorityClass.RealTime;
}