Windows 7小工具没有释放ActiveX对象 [英] Windows 7 Gadget not releasing ActiveX object
问题描述
我正在使用Windows 7小工具,需要从Excel文档中提取数据。问题在于,我检索到我需要的数据后,Excel进程将不会卸载。
I'm working on a Windows 7 gadget that needs to pull data from an excel document. The problem is, is that the Excel process won't unload after I've retrieved the data I need.
这是我在初始化函数中使用的代码:
Here's the code I use in my initialization function:
var Excel = new ActiveXObject("Excel.Application");
Excel.Visible = false;
Excel.DisplayAlerts = false;
var workbooks = Excel.Workbooks;
var workbook = workbooks.Open("\\\\SERVER\\Documents\\Sample.xlsx", 0, true);
var activesheet = workbook.ActiveSheet;
var cell = sheet.Cells(1, 1);
var value = cell.Value;
document.getElementById("content").innerHTML = value;
delete value;
value = null;
delete cell;
cell = null;
delete activesheet;
activesheet = null;
delete workbook;
workbook = null;
delete workbooks;
workbooks = null;
Excel.Quit();
delete Excel;
Excel = null;
这都是包装在一个try-catch块,我可以验证它是否成功。所有的删除和空值分配是我试图释放对COM对象的任何引用,但我似乎缺少一些东西。有没有办法强制Excel进程卸载?
This is all wrapped in a try-catch block and I can verify that it's all succeeding. All the deletes and null assignments are my attempt to release any references to the COM objects, but I seem to be missing something. Is there some way I can force the Excel process to unload?
推荐答案
这只是Internet Explorer / JScript的工作原理引用保持一段时间,直到垃圾回收器运行。如果您将变量设置为 null
,引用应该在一段时间后被垃圾回收。您还可以通过使用JScript和IE可用的(相对未记录的) CollectGarbage()
方法来强制它收集。
This is just how Internet Explorer/JScript works — references are held for a period of time until the garbage collector runs. The reference should be garbage collected after a while if you set the variable to null
. You can also force it to be collected by using the (relatively undocumented) CollectGarbage()
method available to JScript and IE:
var Excel = new ActiveXObject("Excel.Application");
//... blah ...
Excel.Quit();
Excel = null;
window.setTimeout(CollectGarbage, 10);
请注意,您需要在调用<$ c $之前留下少量时间(10ms) c> CollectGarbage(),否则当您调用该函数时,该变量可能尚未被标记为集合。
Note that you need to leave a small amount of time (10ms here) before calling CollectGarbage()
, otherwise when you call the function the variable may not have been marked for collection yet.
这篇关于Windows 7小工具没有释放ActiveX对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!