其实好几天前就想写完这篇博客,因为事情太多。今天才拿出代码来,回故一下。赶快补上。。。。。
以下是在aspx的页面里,调用excel来处理业务后,用完后。回收excel进程的代码:


if
(excel
!=
null
)
{
try
{
int hwnd = excel.Hwnd;
if (book != null )
{
book.Close( true , Missing, Missing);
Marshal.ReleaseComObject(book);
book = null ;
}
excel.Workbooks.Close();
excel.Quit();
Marshal.ReleaseComObject(excel);
excel = null ;
GC.Collect( 20 );
int processID = GetWindowThreadProcessId(hwnd);
if (processID != 0 )
{
Process process = Process.GetProcessById(processID);
process.Kill();
}
}
catch
{
}
}
{
try
{
int hwnd = excel.Hwnd;
if (book != null )
{
book.Close( true , Missing, Missing);
Marshal.ReleaseComObject(book);
book = null ;
}
excel.Workbooks.Close();
excel.Quit();
Marshal.ReleaseComObject(excel);
excel = null ;
GC.Collect( 20 );
int processID = GetWindowThreadProcessId(hwnd);
if (processID != 0 )
{
Process process = Process.GetProcessById(processID);
process.Kill();
}
}
catch
{
}
}
但是。我最近发现,如果页面正在执行中。Ka的一下,把网页关了。excel.exe这个进程会一直在内存中。而且回收IIS应用程序池或是等比较长时间或是再次进行excel。哪个之前挂的excel.exe会一直在。
最后,我发现。是因为异常关闭IE,对于aspx页面,没有能很好的回收进程。所以我在每次调用excel之时,手动进行一次GC回收,
GC.Collect()