我正在使用C#& VS2013和VSTO。我的代码执行完美,但我遇到的一个问题是,当我转到任务管理器并查看详细信息时,Excel仍显示为运行,即使之后,我觉得我已经正确清理了。
这是我用来清理和关闭对Excel的所有引用的语法。只是引用Excel& VSTO,我遗漏了做腿部工作的肉和肉汁,或者这篇文章很长。
我是否有不正确的设置?为什么Excel仍显示在任务管理器中?
namespace ReleaseExcel
{
public partial class Form12 : Form12
{
public static Excel.Worksheet newSeet;
public static Excel._Worksheet currentsheet;
public static Excel._Workbook oWB;
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Workbook activeworkbook;
public Form1()
{
InitializeComponents();
}
private void DoThis()
{
//Showing Declerations to Excel
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Do some more stuff here
//Showing a few more Declerations to Excel
currentsheet = (Excel._Worksheet)(xlWorkBook.ActiveSheet);
Excel.Range last = currentsheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
//Do a bit more stuff
ClearExcel();
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet) != 0) { }
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(currentsheet) != 0) { }
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook) != 0) { }
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) != 0) { }
}
private static void ClearExcel()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
修改
我添加了GC.Collect()
& GC.WaitForPendingFinalizers()
但现在我的语法挂起了
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook) != 0) { }
现在已经坐在这条线上大约5分钟了,是什么导致了冻结?
编辑#2
仍然没有这样的运气。这是代码
namespace ReleaseExcel
{
public partial class Form12 : Form12
{
public static Excel.Worksheet newSeet;
public static Excel._Worksheet currentsheet;
public static Excel._Workbook oWB;
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Workbook activeworkbook;
public Form1()
{
InitializeComponents();
}
public void btnPush_Click(object sender, EventArgs e)
{
DoThis();
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void DoThis()
{
//Showing Declerations to Excel
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Do some more stuff here
//Showing a few more Declerations to Excel
currentsheet = (Excel._Worksheet)(xlWorkBook.ActiveSheet);
Excel.Range last = currentsheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
}
}
}