我在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后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.
我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?
考虑以下代码:
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()
调用时没有被任何其他对象进一步引用,为什么它没有在那里完成?