2

次のコード スニペットがあります。動作します (ディレクトリ内のすべての Word 文書を開いてから閉じます)...しかし、プログラムを完全に終了しても、それ自体はクリーンアップしません。

これは、VB.NET アプリケーションを終了して TaskManager を見ると、アプリケーションを開く前は存在していなかったにもかかわらず、WINWORD.EXE が表示されることを意味します。

私が持っている宣言は次のとおりです。

Dim WordApp As Microsoft.Office.Interop.Word.Application
Dim aDoc As Microsoft.Office.Interop.Word.Document

Dim missing As Object = System.Reflection.Missing.Value
Dim nullobj As Object = System.Reflection.Missing.Value

Dim MYreadOnly As Object = False
Dim isVisible As Object = False

コードは次のとおりです。

Private Sub cmdGenerate_Click(sender As System.Object, e As System.EventArgs) Handles cmdGenerateKeywords.Click

  Dim xmldoc As New XmlDataDocument()
  Dim xmlnode As XmlNodeList
  Dim i As Integer
  Dim fs As FileStream

  WordApp = New Microsoft.Office.Interop.Word.Application
  WordApp.Visible = False

  For Each f As FileInfo In New DirectoryInfo(txtFolderName.Text).GetFiles("*.docx")
    ' Open the document that was chosen by the dialog
    aDoc = WordApp.Documents.Open(f.FullName, missing, [MYreadOnly], _
           missing, missing, missing, missing, missing, missing, missing, _
           missing, isVisible)
    'aDoc.Close()
    aDoc = Nothing
  Next

  'Close the Word Document
  'aDoc.Close(nullobj, nullobj, nullobj)
  WordApp.Application.Quit()
  WordApp = Nothing
End Sub

ご覧のとおり、Word 文書と Word アプリケーション自体の閉鎖に関して、さまざまなステートメントにコメントを付けたり、コメントを外したりしました。私が試したものは、その厄介なWINWORD.EXEを取り除くことができないようです

何かがロックされているようで、閉じられませんか? それですか?

4

2 に答える 2

2

この記事に示されているように、ガベージ コレクターを明示的に実行します。

 // Clean up the unmanaged Word COM resources by forcing a garbage 
 // collection as soon as the calling function is off the stack (at 
 // which point these objects are no longer rooted).

 GC.Collect();
 GC.WaitForPendingFinalizers();
 // GC needs to be called twice in order to get the Finalizers called 
 // - the first time in, it simply makes a list of what is to be 
 // finalized, the second time in, it actually is finalizing. Only 
 // then will the object do its automatic ReleaseComObject.
 GC.Collect();
 GC.WaitForPendingFinalizers();

上記のリンクにもかかわらず、私の経験では、一度実行するだけで十分です。しかし、2 回目の呼び出しはエラーをスローしないので、このようにします。

于 2013-07-12T14:03:18.170 に答える