首页 > Web开发 > 详细

常见.NET功能代码汇总 (3)

时间:2017-06-24 16:09:03      阅读:317      评论:0      收藏:0      [点我收藏+]

33,彻底关闭Excel进程

.NET中使用Excel属于使用非托管资源,使用完成后一般都要用GC回收资源,但是,调用GC的位置不正确,Excel进程可能无法彻底关闭,如下面的代码:

static void OpenExcelTest(int j)
        {
            //Application excel = null;
            excel = new Application();
            excel.Visible = true;
            excel.Workbooks.Open("d:\\A1000.xla");
            Workbook wb = excel.Application.Workbooks.Open("d:\\Book1.xlsx");
            Worksheet sh = wb.Worksheets.Item["Sheet1"];
            object[,] ssss = sh.Range[sh.Cells[1.1], sh.Cells[3, 1]].Value2;
            Console.WriteLine("opened excel no. {0}", j);
            Console.ReadLine();

            try
            {
                //尝试程序关闭Excel进程
                wb.Close(false);
                sh = null;
                wb = null;
                excel.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("用户已经手工结束了Excel进程,内部错误消息:{0}",ex.Message );
            }
            
            int generation = System.GC.GetGeneration(excel);

            //No.1
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(sh);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
          
            excel = null;
            //No.2
            //GC.Collect(generation);

            Console.WriteLine("close excel no. {0}", j);
            Console.ReadLine();
        }

在上面的代码中,如果取消 No.1,No.2位置处的注释,方法结束后,Excel进程是无法结束的,解决办法,只需要把
GC.Collect();
这行代码写到方法之外即可。


Application excel = null;
这个Excel应用程序对象定义在方法内或者外都是可以的,哪怕定义一个静态变量,结果都没有影响。

 

常见.NET功能代码汇总 (3)

原文:http://www.cnblogs.com/bluedoctor/p/7073534.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!