2012-06-09 46 views
1

什麼是「免費」這個對象的替代品?它通常在調用.Exit()方法時發生,但在這種情況下,我不能這樣做,因爲應該關閉單詞應用程序實例的用戶。我以爲要做wordApp = null或致電GC.Collect();什麼是最好的解決方案,爲什麼?提前致謝。如何「免費」Microsoft.Office.Interop.Word.Application wordApp實例?

我使用這個目前:

public static void Free() 
    { 
     if (wordApp != null) 
     { 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); 
      GC.Collect(); 
     } 
    } 
+2

設爲空值。做marshal.releasecomobject並調用GC.collect –

+0

謝謝我現在正在使用它。 – Jack

回答

3

最積極的辦法,以確保互操作對象正常釋放是使用雙Collect - WaitForPendingFinalizers模式,改編自Releasing COM Objects

Marshal.ReleaseComObject(wordApp); 
wordApp = null; 
GC.Collect(); 
GC.WaitForPendingFinalizers(); 
GC.Collect(); 
GC.WaitForPendingFinalizers(); 

託管世界和非託管世界之間的一個互操作領域,您需要特別小心的是乾淨地釋放COM對象當你完成他們的時候。在前面的例子中,我們設法實現了我們使用標準垃圾回收所需的所有行爲。唯一輕微的提高是撥打GC.Collect兩次,以確保任何可用於收集但在第一次掃描中倖存的記憶都是在第二次掃描中收集的。

+0

如果沒有設置wordApp.Quit(saveOption),它還沒有從正在運行的進程中釋放,您必須將保存選項設置爲true或false,並將其設置爲false並像魅力一樣工作。 –

3

一個不太侵略性的方式做到這一點是這樣的

 // Make sure to exit app first 
     object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; 
     object originalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat; 
     object routeDocument = false; 

     ((_Application)wordApp).Quit(ref saveOption, ref originalFormat, ref routeDocument); 

     if (wordApp!= null) 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); 

     // Set to null 
     wordApp= null; 

確保然而,所有文件已經關閉,或關閉並保存!

-1

From MSDN

爲了應對這些情況時ReleaseComObject的返回值大於零,則可以調用該方法在一個循環中執行ReleaseComObject的,直到返回的值爲零:

Dim wrd As New Microsoft.Office.Interop.Word.Application 
Dim intRefCount As Integer 
Do 
    intRefCount = System.Runtime.InteropServices.Marshal.ReleaseComObject(wrd) 
Loop While intRefCount > 0 
wrd = Nothing