在CSDN上看到长江支流发表这个主题,真的是很感谢!但有此细节如何没有做好还是不能释放资源,在此补充一下
实现代码
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
/// <summary>
/// 释放Excel所占的内存。
/// </summary>
public void ReleaseComObjectExcel()
{
if (m_objExcel != null)
{
m_objExcel.UserControl = false;
//m_objExcel.DisplayAlerts = false;
//m_objExcel.Quit();
//m_objBooks.Close();
ReleaseObj(ref m_objFont);
ReleaseObj(ref m_objRange);
ReleaseObj(ref m_objSheet);
ReleaseObj(ref m_objSheets);
ReleaseObj(ref m_objBook);
ReleaseObj(ref m_objBooks);
int generation = GC.GetGeneration(m_objExcel);
ReleaseObj(ref m_objExcel);
GC.Collect(generation);
m_oMissing = null;
}
}
/// <summary>
/// 释放对象,内部调用
/// </summary>
/// <param name="o"></param>
private void ReleaseObj(ref object obj)
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
最主要记住还存在引用关系的变量清除为空,这个切记
实现代码
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/// <summary>
/// 释放Excel所占的内存。
/// </summary>
public void ReleaseComObjectExcel()
{
if (m_objExcel != null)
{
m_objExcel.UserControl = false;
//m_objExcel.DisplayAlerts = false;
//m_objExcel.Quit();
//m_objBooks.Close();
ReleaseObj(ref m_objFont);
ReleaseObj(ref m_objRange);
ReleaseObj(ref m_objSheet);
ReleaseObj(ref m_objSheets);
ReleaseObj(ref m_objBook);
ReleaseObj(ref m_objBooks);
int generation = GC.GetGeneration(m_objExcel);
ReleaseObj(ref m_objExcel);
GC.Collect(generation);
m_oMissing = null;
}
}
/// <summary>
/// 释放对象,内部调用
/// </summary>
/// <param name="o"></param>
private void ReleaseObj(ref object obj)
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
最主要记住还存在引用关系的变量清除为空,这个切记