我在C#中编写了一个Excel包装器,以便允许在批处理过程中运行Excel工作簿(在JobScheduler下).我的问题是……
如果代码运行时间过长或需要通过作业调度程序终止,则包装器需要处理此终止事件.为此,我补充道
SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck),true);
进入代码.在ConsoleCtrlCheck方法中,我调用一个公共出口例程(在正常或终止情况下使用).根据MS建议,此路由执行以下操作.
但是,如果VBA代码仍在运行,则Interop对象将不响应工作簿关闭或应用程序退出调用.这可能是因为一切都很慢或者因为发出了模态对话框.
为了解决这个问题,我在这个常见程序的开头添加了以下内容……
>创建新线程以运行KillExcel方法
> KillExcel方法在指定时间内休眠(因此正常的退出代码有机会工作)然后杀死进程
>如果正常代码有效,则在线程上调用Abort
private static void Cleanup() { // Give this X seconds then terminate mKillThread = new Thread(KillExcel); mKillThread.IsBackground = false; mKillThread.Start(); ... // close the workbooks and excel application // Marshal.FinalReleaseComObject etc GC.Collect(); GC.WaitForPendingFinalizers(); // Not sure if necessary but makes sure Process gone try { Process p = Process.GetProcessById(mExcelPid); p.WaitForExit(); } catch(ArgumentException) {} mKillThread.Abort(); } private static void KillExcel() { Thread.Sleep(Settings.Default.KillWaitMilliSeconds); if (mLog.IsInfoEnabled) mLog.Info(string.Format("Waited {0} seconds,killing Excel process [{1}]",Settings.Default.KillWaitMilliSeconds/1000,mExcelPid)); try { Process p = Process.GetProcessById(mExcelPid); if (!p.HasExited) p.Kill(); } catch(ArgumentException) { } }
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。