使用 C#操作 Excel 的 COM 组件的过程中,最后把 EXCEL 进程关闭掉是十分重要的。
首先第一种是利用.net 的 GC,即垃圾回收器。代码如下:
C#代码
1. usingSystem;
2. usingSystem.Collections.Generic;
3. usingSystem.Text;
4. usingSystem.Runtime.InteropServices;
5.
6. namespaceExcelTest
7. {
8. classDataOutput
9. {
10. staticvoidMain(string[]args)
11. {
12. Excel.Applicationapp=newExcel.ApplicationClass();
13. Excel.WorkbookwBook=app.Workbooks.Add(true);
14. Excel.WorksheetwSheet=wBook.Worksheets[1]asExcel.Wor
ksheet;
15. app.Visible=true;
16.
17. System.Runtime.InteropServices.Marshal.ReleaseComObject(w
Sheet);
18. System.Runtime.InteropServices.Marshal.ReleaseComObject(w
Book);
19. System.Runtime.InteropServices.Marshal.ReleaseComObject(a
pp);
20. GC.Collect();//显式调用 GC
21.
22. Console.Read();
23. }
24. }
25. }
关注后面四行,System.Runtime.InteropServices.Marshal 类主要提供对非受托管内存
的操作。对于函数 ReleaseComObject,在 MSDN 上的解释是“该运行库可调用包装具有引
用计数,每次将COM 接口指针映射到该运行库可调用包装时,此引用计数都将递增。
ReleaseComObject 方法递减运行库可调用包装的引用计数。当引用计数达到零时,运行
库将释放非托管COM 对象上的所有引用。”即断开对对象的引用,这样 GC 发现对象不会
再被使用,那么就会回收它。
评论0