在创建Excel COM对象在foreach循环中创建时是否会释放内存 [英] Will memory be released when creating Excel COM objects are creating in foreach loop

查看:94
本文介绍了在创建Excel COM对象在foreach循环中创建时是否会释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用VS 2012,.NET 4.5,Excel Interop 14



我正在阅读Excel文件并正在处理所有工作表以从数字中提取数据他们我很确定我正在使用下面的代码正确释放所有内存(来源)。



 Marshal.ReleaseComObject(oSheet); 
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);

oSheet = null ;
oWB = null ;
oXL = null ;
GC.GetTotalMemory( false );
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory( true );





所以我的问题是,在下面的代码中,foreach循环创建的工作表是否会正确释放内存?

  foreach  var  oSheet  in  oWB.Sheets)
{
...下一块代码
}





或者我必须这样做吗?

  for  int  i =  1 ; i <  oWB.Sheets.Count; i ++)
{
Excel._Worksheet oSheet = oWB.Sheets [一世];
...下一个代码块

Marshal.ReleaseComObject(oSheet);
oSheet = null ;
}

解决方案

您正在循环工作表。无需在此发布任何内容。这些工作表已经在内存中,你正在循环它们。



最后,你只需要发布工作簿并退出应用程序。


确定。最初的问题不够明确......抱歉。这可能是在回答我自己的问题。使用foreach循环,这似乎是访问工作表的属性和数据的唯一方法。

  foreach  var  oSheet  in  oWB.Sheets)
{
Excel._Worksheet sheet = oSheet as Excel._Worksheet;
if (sheet.Name.Contains(


TEST_VAL)
{
function1( sheet);
}
Marshal.ReleaseComObject(sheet);
sheet = null ;
}


Using VS 2012, .NET 4.5, Excel Interop 14

I'm reading in an Excel file and working though all the sheets to extract data from a number of them. I'm fairly certain I'm releasing all the memory correctly with the code below (source).

Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
 
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);



So my question is, in the code below, will the sheet created by the foreach loop properly release the memory?

foreach (var oSheet in oWB.Sheets)
{
    ...next chunk of code
}



Or do I have to do it like this?

for (int i = 1; i < oWB.Sheets.Count; i++)
{
    Excel._Worksheet oSheet = oWB.Sheets[i];
    ...next chunk of code    

    Marshal.ReleaseComObject(oSheet);
    oSheet = null;
}

解决方案

You are looping through the sheets. No need to release anything here. The sheets are already in memory and you are looping through them.

Al last, you just need to release the workbook and quit the application.


OK. The initial question wasn't clear enough...sorry. This might be answering my own question. Using a foreach loop, this seems to be the only way to access properties and data of the sheet.

foreach (var oSheet in oWB.Sheets)
{
    Excel._Worksheet sheet = oSheet as Excel._Worksheet;
    if(sheet.Name.Contains(


TEST_VAL ) { function1(sheet); } Marshal.ReleaseComObject(sheet); sheet = null; }


这篇关于在创建Excel COM对象在foreach循环中创建时是否会释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆