我的单线程系统接收一个html,一个TIdHttp,并用IHTMLDocument2处理这个html,如下所示:
if IDocTabela = nil then
IDocTabela := CreateComObject(Class_HTMLDOcument) as IHTMLDocument2
else
IDocTabela.clear;
IDocTabela.designMode := 'on';
if IENovo = False then
while IDocTabela.readyState <> 'complete' do
Application.ProcessMessages;
v := VarArrayCreate([0, 0], VarVariant);
v[0] := xHtml;
IDocTabela.Write(PSafeArray(System.TVarData(v).VArray));
IDocTabela.designMode := 'off';
if IENovo = False then
while IDocTabela.readyState <> 'complete' do
Application.ProcessMessages;
for q := 0 to (IDocTabela.all.tags('TABLE') as IHTMLElementCollection).Length -1 do
begin
ovTable := (IDocTabela.all.tags('TABLE') as IHTMLElementCollection).item(q, 0);
for i := 0 to (ovTable.Rows.Length - 1) do
begin
for j := 0 to (ovTable.Rows.Item(i).Cells.Length - 1) do
begin
sTemp := TrimRight(TrimLeft(ovTable.Rows.Item(I).Cells.Item(J).InnerText));
if (sTemp = 'Item') = true then
begin
bSai := True;
Break;
end;
end;
if bSai = True then
Break;
end;
if bSai = True then
Break;
end;我的问题是,这段代码每3秒执行一次,每次执行这段代码,内存消耗都会增加1.000k,这个应用程序将消耗大量内存,并且随着时间的推移会变慢,直到它锁定,导致内存增加的两行代码是:
IDocTabela.Write(PSafeArray(System.TVarData(v).VArray));和
ovTable := (IDocTabela.all.tags('TABLE') as IHTMLElementCollection).item(q, 0);注意:我总是销毁用FreeAndNil()创建的IHTMLDocument2组件。你知道如何改进这段代码,这样内存消耗就会停止吗?
谢谢!
发布于 2015-06-25 06:45:52
我总是销毁用FreeAndNil()创建的IHTMLDocument2组件
你不能这么做。没有IHTMLDocument2 组件。您正在创建实现IHTMLDocument2 接口的COM对象的实例,并且该接口对引用进行了计数。它的底层实现对象不是基于TObject的(因为它一开始就不是用Delphi语言编写的)。当接口的引用计数降到0时,它会自动释放其基础对象。只要让变量超出作用域即可。如果必须手动递减引用计数,请使用FreeAndNil()将接口设置为nil
IDocTabela := CreateComObject(Class_HTMLDOcument) as IHTMLDocument2
...
IDocTabela := nil;也就是说,还有另一种方法可以将HTML加载到IHTMLDocument2中--查询IPersistStreamInit接口,然后调用它的Load()方法,该方法接受IStream作为输入。无需将文档置于设计模式,也无需处理窗口消息。您可以将HTML放入TStringStream或TMemoryStream中,然后将其包装在TStreamAdapter中,从而为您的HTML获取一个IStream。
https://stackoverflow.com/questions/31036591
复制相似问题