相关疑难解决方法(0)

如何正确清理Excel互操作对象?

我在C#(ApplicationClass)中使用Excel互操作,并在我的finally子句中放置了以下代码:

while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)

虽然这种工作,Excel.exe即使我关闭Excel后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.

我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?

c# excel interop com-interop

733
推荐指数
20
解决办法
30万
查看次数

了解.NET中的垃圾收集

考虑以下代码:

public class Class1
{
    public static int c;
    ~Class1()
    {
        c++;
    }
}

public class Class2
{
    public static void Main()
    {
        {
            var c1=new Class1();
            //c1=null; // If this line is not commented out, at the Console.WriteLine call, it prints 1.
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine(Class1.c); // prints 0
        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,即使main方法中的变量c1超出范围并且在GC.Collect()调用时没有被任何其他对象进一步引用,为什么它没有在那里完成?

.net c# garbage-collection

161
推荐指数
2
解决办法
5万
查看次数

标签 统计

c# ×2

.net ×1

com-interop ×1

excel ×1

garbage-collection ×1

interop ×1