【问题标题】:How to force quit Word using C# Interop如何使用 C# Interop 强制退出 Word
【发布时间】:2015-04-29 08:34:06
【问题描述】:

如何保证 MS Word 进程退出(使用 C# 互操作库)?

我目前的做法:

// close word document ("doc")
((_Document)doc).Close(SaveChanges: WdSaveOptions.wdDoNotSaveChanges);
if (doc != null)
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
    doc = null;
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

// close word application ("word")
((_Application)word).Quit(false);
if (word != null)
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
    word = null;
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

// and here is how it fails
Process[] pname = Process.GetProcessesByName("WINWORD");
Assert.IsTrue(pname.Length == 0);

来源:

c# MSOffice Interop Word will not kill winword.exe

Disposing of Microsoft.Office.Interop.Word.Application

Microsoft.Interop object won't quit or "release"

Excel interop COM doesn't close

Ambiguity in Word Interop code

【问题讨论】:

  • 再次检查您是否违反了两点规则,并且您正在处理您创建的每个办公对象,就像您的示例中的对象一样。如果您仍然看到该过程,我也不会感到惊讶,因为您在清理代码后立即检查它。
  • 是的,一切都是时机——我现在意识到你得等一会儿。谢谢

标签: c# process ms-word office-interop quit


【解决方案1】:

如果使用 GC 方法刷堆,则无需使用 ReleaseComObject。另请注意,您需要调用 GC 方法两次:

 GC.Collect();
 GC.WaitForPendingFinalizers();
 GC.Collect();
 GC.WaitForPendingFinalizers();

无论如何,我始终建议您使用System.Runtime.InteropServices.Marshal.ReleaseComObject 在您使用完Office (Word) 对象后释放它。然后在 Visual Basic 中将变量设置为 Nothing(在 C# 中为 null)以释放对对象的引用。您可以在Systematically Releasing Objects 文章中阅读更多相关信息。它与 Outlook 相关,但相同的规则可以应用于任何 Office 应用程序(包括 Word)。

【讨论】:

    【解决方案2】:

    无论如何这对我有用

    Word.Application app = null;
    Word.Document doc = null;
    Word.Tables tables = null;
    Word.ContentControls mainControls = null;
    
    try
    {
        app = new Word.Application();
        app.ScreenUpdating = false;
        app.Visible = false;
        app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
        doc = app.Documents.Open(fileName);
        tables = doc.Tables;
            //.. my code 
            if (tables.Count < 1)
            val = mainControls[2].Range.Text ?? "";
            //end of my code
        }
    catch (Exception exc) { G.log(exc); }
    finally
    {
        //CLEAN UP
        GC.Collect();
        GC.WaitForPendingFinalizers(); 
        if (mainControls != null)
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(mainControls);
        if (tables != null)
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(tables);
        if (doc != null)
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc);
        app.Quit();
        if (app != null)
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多