Delphi中的Javascript TWebBrowser,关闭线程

Delphi中的Javascript TWebBrowser,关闭线程,第1张

概述我试图在delphi中构建一个允许用户使用谷歌地图的系统.一切正常,但我注意到每次创建一个新的TWebBrowser对象并加载处理谷歌地图的javascript时,会生成许多新的线程. 我的问题是,即使一旦web浏览器被破坏(并且它被明确地销毁),创建的线程仍然存在.我正在设计这个程序有很长的运行时间和谷歌地图的打开和关闭发生多次,因此,一段时间后,生成了很多线程,并没有终止该程序显着减慢. 有没 我试图在delphi中构建一个允许用户使用谷歌地图的系统.一切正常,但我注意到每次创建一个新的TWebbrowser对象并加载处理谷歌地图的JavaScript时,会生成许多新的线程.

我的问题是,即使一旦web浏览器被破坏(并且它被明确地销毁),创建的线程仍然存在.我正在设计这个程序有很长的运行时间和谷歌地图的打开和关闭发生多次,因此,一段时间后,生成了很多线程,并没有终止该程序显着减慢.

有没有办法自己销毁这些线程,或者我做错了导致线程持续存在?

我的程序基于以下代码:

constHTMLStr: AnsiString ='<HTML> '+    '<head> '+'<Meta name="vIEwport" content="initial-scale=1.0,user-scalable=yes" /> '+'<script type="text/JavaScript" src="http://maps.Google.com/maps/API/Js?sensor=true">        </script> '+'<script type="text/JavaScript"> '+''+''+'  var geocoder; '+'  var map;  '+'  var trafficLayer;'+'  var bikeLayer;'+'  var markersArray = [];'+''+''+'  function initialize() { '+'    geocoder = new Google.maps.Geocoder();'+'    var latlng = new Google.maps.LatLng(40.714776,-74.019213); '+'    var myOptions = { '+'      zoom: 13,'+'      center: latlng,'+'      mapTypeID: Google.maps.MapTypeID.ROADMAP '+'    }; '+'    map = new Google.maps.Map(document.getElementByID("map_canvas"),myOptions); '+'    trafficLayer = new Google.maps.TrafficLayer();'+'    bikeLayer = new Google.maps.BicyclingLayer();'+'    map.set("streetVIEwControl",false);'+'  } '+''+''+'  function codeAddress(address) { '+'    if (geocoder) {'+'      geocoder.geocode( { address: address},function(results,status) { '+'        if (status == Google.maps.GeocoderStatus.OK) {'+'          map.setCenter(results[0].geometry.location);'+'          PutMarker(results[0].geometry.location.lat(),results[0].geometry.location.lng(),results[0].geometry.location.lat()+","+results[0].geometry.location.lng());'+'        } else {'+'          alert("Geocode was not successful for the following reason: " + status);'+'        }'+'      });'+'    }'+'  }'+''+''+'  function GotolatLng(Lat,Lang) { '+'   var latlng = new Google.maps.LatLng(Lat,Lang);'+'   map.setCenter(latlng);'+'   PutMarker(Lat,Lang,Lat+","+Lang);'+'  }'+''+''+'function ClearMarkers() {  '+'  if (markersArray) {        '+'    for (i in markersArray) {  '+'      markersArray[i].setMap(null); '+'    } '+'  } '+'}  '+''+'  function PutMarker(Lat,Msg) { '+'   var latlng = new Google.maps.LatLng(Lat,Lang);'+'   var marker = new Google.maps.Marker({'+'      position: latlng,'+'      map: map,'+'      Title: Msg+" ("+Lat+","+Lang+")"'+'  });'+' markersArray.push(marker); '+'  }'+''+''+'  function TrafficOn()   { trafficLayer.setMap(map); }'+''+'  function TrafficOff()  { trafficLayer.setMap(null); }'+''+''+'  function BicyclingOn() { bikeLayer.setMap(map); }'+''+'  function BicyclingOff(){ bikeLayer.setMap(null);}'+''+'  function StreetVIEwOn() { map.set("streetVIEwControl",true); }'+''+'  function StreetVIEwOff() { map.set("streetVIEwControl",false); }'+''+''+'</script> '+'</head> '+'<body onload="initialize()"> '+'  <div ID="map_canvas" ></div> '+'</body> '+'</HTML> ';procedure TfrmMain.FormCreate(Sender: TObject);var  aStream     : TMemoryStream;begin   Webbrowser1.Navigate('about:blank');    if Assigned(Webbrowser1.document) then    begin      aStream := TMemoryStream.Create;      try     aStream.WriteBuffer(Pointer(HTMLStr)^,Length(HTMLStr));     //aStream.Write(HTMLStr[1],Length(HTMLStr));     aStream.Seek(0,soFromBeginning);     (Webbrowser1.document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));  finally     aStream.Free;  end;  HTMLWindow2 := (Webbrowser1.document as IHTMLdocument2).parentwindow;end;end;procedure TfrmMain.buttonGotolocationClick(Sender: TObject);begin   HTMLWindow2.execScript(Format('GotolatLng(%s,%s)',[Latitude.Text,Longitude.Text]),'JavaScript');end;procedure TfrmMain.buttonClearMarkersClick(Sender: TObject);begin  HTMLWindow2.execScript('ClearMarkers()','JavaScript')end;procedure TfrmMain.buttonGotoAddressClick(Sender: TObject);var   address    : string;begin   address := MemoAddress.lines.Text;   address := StringReplace(StringReplace(Trim(address),#13,' ',[rfReplaceAll]),#10,[rfReplaceAll]);   HTMLWindow2.execScript(Format('codeAddress(%s)',[QuotedStr(address)]),'JavaScript');end;procedure TfrmMain.CheckBoxStreeVIEwClick(Sender: TObject);begin    if CheckBoxStreeVIEw.Checked then     HTMLWindow2.execScript('StreetVIEwOn()','JavaScript')    else     HTMLWindow2.execScript('StreetVIEwOff()','JavaScript');end;procedure TfrmMain.CheckBoxBicyclingClick(Sender: TObject);begin    if CheckBoxBicycling.Checked then     HTMLWindow2.execScript('BicyclingOn()','JavaScript')    else     HTMLWindow2.execScript('BicyclingOff()','JavaScript'); end;procedure TfrmMain.CheckBoxTrafficclick(Sender: TObject);begin    if CheckBoxTraffic.Checked then     HTMLWindow2.execScript('TrafficOn()','JavaScript')    else     HTMLWindow2.execScript('TrafficOff()','JavaScript'); end;end.

程序使用一个基本的析构函数来设置HTMLWindow导航到about:blank.
提前致谢

解决方法 这不回答这个问题,它只是简化了要模拟的问题.

查看每次单击按钮后运行的线程数.它使用Simple Google Maps example,所以问题甚至不在你的JavaScript部分.

Unit1 – 包含主窗体,其中只是一个带有OnClick事件处理程序的按钮

unit Unit1;interfaceuses  windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,PsAPI,TlHelp32,Unit2;type  TForm1 = class(TForm)    button1: Tbutton;    procedure button1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;implementation{$R *.dfm}function GetThreadCount(const APID: Cardinal): Integer;var  NextProc: Boolean;  ProcHandle: THandle;  ThreadEntry: TThreadEntry32;begin  Result := 0;  ProcHandle := Createtoolhelp32Snapshot(TH32CS_SNAPTHREAD,0);  if (ProcHandle <> INVALID_HANDLE_VALUE) then  try    ThreadEntry.DWSize := SizeOf(ThreadEntry);    NextProc := Thread32First(ProcHandle,ThreadEntry);    while NextProc do    begin      if ThreadEntry.th32OwnerProcessID = APID then      Inc(Result);      NextProc := Thread32Next(ProcHandle,ThreadEntry);    end;  finally    CloseHandle(ProcHandle);  end;end;procedure TForm1.button1Click(Sender: TObject);var  ModalForm: TForm2;begin  ModalForm := TForm2.Create(nil);  try    ModalForm.ShowModal;  finally    ModalForm.Free;  end;  ShowMessage('Thread count: ' +     IntToStr(GetThreadCount(GetCurrentProcessID)));end;end.

Unit2 – 包含带有TWebbrowser的表单和表单的OnCreate事件处理程序

unit Unit2;interfaceuses  windows,oleCtrls,SHDocVw,ActiveX;type  TForm2 = class(TForm)    Webbrowser1: TWebbrowser;    procedure FormCreate(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form2: TForm2;implementation{$R *.dfm}const  HTMLString: AnsiString =    '<!DOCTYPE HTML>' +    '<HTML>' +    '  <head>' +    '    <Title>Google Maps JavaScript API v3 Example: Map Simple</Title>' +    '    <Meta name="vIEwport"' +    '        content="wIDth=device-wIDth,initial-scale=1.0,user-scalable=no">' +    '    <Meta charset="UTF-8">' +    '    <style type="text/CSS">' +    '      HTML,body,#map_canvas {' +    '        margin: 0;' +    '        padding: 0;' +    '        height: 100%;' +    '      }' +    '    </style>' +    '    <script type="text/JavaScript"' +    '        src="http://maps.GoogleAPIs.com/maps/API/Js?sensor=false"></script>' +    '    <script type="text/JavaScript">' +    '      var map;' +    '      function initialize() {' +    '        var myOptions = {' +    '          zoom: 8,' +    '          center: new Google.maps.LatLng(-34.397,150.644),' +    '          mapTypeID: Google.maps.MapTypeID.ROADMAP' +    '        };' +    '        map = new Google.maps.Map(document.getElementByID(''map_canvas''),' +    '            myOptions);' +    '      }' +    '      Google.maps.event.addDomListener(window,''load'',initialize);' +    '    </script>' +    '  </head>' +    '  <body>' +    '    <div ID="map_canvas"></div>' +    '  </body>' +    '</HTML>';procedure TForm2.FormCreate(Sender: TObject);var  HTMLStream: TMemoryStream;begin  Webbrowser1.Navigate('about:blank');  if Assigned(Webbrowser1.document) then  begin    HTMLStream := TMemoryStream.Create;    try      HTMLStream.WriteBuffer(Pointer(HTMLString)^,Length(HTMLString));      HTMLStream.Seek(0,soFromBeginning);      (Webbrowser1.document as IPersistStreamInit).Load(TStreamAdapter.Create(HTMLStream));    finally      HTMLStream.Free;    end;  end;end;end.
总结

以上是内存溢出为你收集整理的Delphi中的Javascript TWebBrowser,关闭线程全部内容,希望文章能够帮你解决Delphi中的Javascript TWebBrowser,关闭线程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1277824.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存