簡體   English   中英

是否未釋放COM對象未分配給var?

[英]Does matter COM object not assigned to var is not released?

如果我使用這樣的代碼,將釋放所有非托管COM對象

var worksheet = new Application().Workbooks.Add().Worksheets.Add();
Marshal.ReleaseComObject(worksheet);

而不是像這樣的代碼

var excel = new Application();
var workbook = excel.Workbooks.Add();
var worksheet = workbook.Worksheets.Add();
Marshal.ReleaseComObject(excel);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(worksheet);

如果有一些文檔,請發送回答鏈接。

實際上,兩個代碼示例都將在后台運行Excel進程。 例如,您需要在應用程序對象上調用Application.Quit() 以下作品:

private static void DoExcel()
    {
        var application = new Application();
        var workbook = application.Workbooks.Add();
        var worksheet = workbook.Worksheets.Add();

        // Name that this will be saved as
        string name = workbook.FullName + ".xlsx";

        string fullPath = Path.Combine(Directory.GetCurrentDirectory(), name);
        // If a file of the same name exists, delete it so that we won't be prompted if
        // we want to overwrite it when we save
        if (File.Exists(fullPath))
            File.Delete(fullPath);

        // Save the workbook - otherwise we may be prompted as to whether we want to save when we go to quit
        workbook.Save();

        // Quit the application
        application.Quit();

        // Release the references
        Marshal.ReleaseComObject(worksheet);
        Marshal.ReleaseComObject(workbook);
        Marshal.ReleaseComObject(application);

        // Release the .NET reference and run the garbage collector now to make sure the application is closed immediately
        worksheet = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

還有一些值得記住的好東西:我沒有在這里使用它,但是有一個Marshal.FinalReleaseComObject方法在這些情況下非常有用。 此外,我再次在我的代碼示例中沒有使用它,但Marshal.ReleaseComObject方法返回當前計數,因此如果您想確保計數達到零,您可以始終在循環中執行釋放:

while (Marshal.ReleaseComObject(comObject) > 0) { }

您也可以將其用於調試目的 - 例如

int count = Marshal.ReleaseComObject(comObject);
Trace.TraceInformation("Current COM object reference count: " + count.ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM