XmlHttpRequest内存泄露问题解决方案

最近做项目遇到一个比较普遍的问题:Ajax定时获取WebService数据时会出现内存泄露。

网上百度了很多解决方案都没能解决,有些方法在一小段时间内确实能有一定的内存回收,但是经过十几个小时的运行后,IE的内存依然增长到很大。

最终,通过google(看来真是验证了那句话:技术帖还是靠谷歌)找到了老外的解决方法。

代码如下:

 1 //测试1
 2         var interval;        
 3         function fire() {
 4             interval = setInterval(GetCount, 1000);
 5         }
 6 
 7         function GetCount() {
 8             var xhr = new XMLHttpRequest();
 9 
10             xhr.open("POST", "C.asmx/GetCount", true);
11             xhr.onreadystatechange = function (event) {
12                 if (xhr.readyState == 4 && xhr.status == 200) {
13                     document.getElementById("tdmsg").innerHTML = "测试1:" + xhr.responseText;
14                     xhr.onreadystatechange = new Function;
15                     xhr = null;
16                 }
17             };
18             xhr.send(null);
19         }
20 
21         fire();
22 
23         //测试2
24         var interval2;
25         function fire2() {
26             interval2 = setInterval(GetCount2, 200);
27         }
28 
29         function GetCount2() {
30             var xhr = new XMLHttpRequest();
31 
32             xhr.open("POST", "D.asmx/GetCount", true);
33             xhr.onreadystatechange = function (event) {
34                 if (xhr.readyState == 4 && xhr.status == 200) {
35                     document.getElementById("testdiv").innerHTML = "测试2:" + xhr.responseText;
36                     xhr.onreadystatechange = new Function;
37                     xhr = null;
38                 }
39             };
40             xhr.send(null);
41         }
42 
43         fire2();
44 
45         //测试3
46         var interval3;
47         function fire3() {
48             interval3 = setInterval(GetCount3, 300);
49         }
50 
51         function GetCount3() {
52             var xhr = new XMLHttpRequest();
53 
54             xhr.open("POST", "E.asmx/GetCount", true);
55             xhr.onreadystatechange = function (event) {
56                 if (xhr.readyState == 4 && xhr.status == 200) {
57                     document.getElementById("testdiv1").innerHTML = "测试3:" + xhr.responseText;
58                     xhr.onreadystatechange = new Function;
59                     xhr = null;
60                 }
61             };
62             xhr.send(null);
63         }
64 
65         fire3();

一共三个WebService的调用,返回简单的数据累加。
这里采用三个Webservice主要是测试IE的稳定性。

WebService代码如下,三个都一样:

 1 public class C : System.Web.Services.WebService
 2     {
 3 
 4         private static long count = 0;
 5 
 6         [WebMethod]
 7         public string GetCount()
 8         {
 9             
10             return (++count).ToString();
11         }
12     }

IE运行效果:

其中测试1采用了1秒的调用间隔,便于统计运行时间:

测试结果:
初始内存:

运行21617秒(360分钟左右)后:

内存:

6个小时的压力测试IE内存增加了10M左右,符合。因为之前的方案基本上一个小时就会有5M左右的内存增加。

原文地址:https://www.cnblogs.com/jiewei915/p/2758073.html