[转]HttpWebRequest使用注意(发生阻塞的解决办法)

 1 HttpWebRequest myRequest = null;
2 HttpWebResponse myResponse = null;
3 Stream reqStream = null;
4 Stream resStream = null;
5
6 try
7 {
8 byte[] data = System.Text.Encoding.Default.GetBytes(param);
9
10 myRequest = (HttpWebRequest)WebRequest.Create(url);
11 myRequest.Method = "POST";
12 myRequest.KeepAlive = true;
13 myRequest.ContentType = "application/octet-stream";
14 myRequest.ContentLength = data.Length;
15 reqStream = myRequest.GetRequestStream();
16 reqStream.Write(data, 0, data.Length);
17 reqStream.Close();
18
19 myResponse = (HttpWebResponse)myRequest.GetResponse();
20 resStream = myResponse.GetResponseStream();
21 data = new byte[512];
22 int count = 0;
23 UIFactory.zZRK_MODIForm.memStream = new MemoryStream();
24 while ((count = resStream.Read(data, 0, data.Length)) > 0)
25 {
26 UIFactory.zZRK_MODIForm.memStream.Write(data, 0, count);
27 }
28 resStream.Close();
29
30 }
31 catch
32 {
33 }
34 finally
35 {
36 if (resStream != null)
37 {
38 resStream.Close();
39 }
40 if (reqStream != null)
41 {
42 reqStream.Close();
43 }
44 if (myResponse != null)
45 {
46 myResponse.Close();
47 }
48 }

大家看下这段程序,有问题吗?乍一看,好像没有什么问题,所有的流都释放了,Response也释放了。。不过如果你写个循环无限次发起请求,你会发现,运行不了几次就阻塞了。为什么呢?大家看下面的代码

 1 HttpWebRequest myRequest = null;
2 HttpWebResponse myResponse = null;
3 Stream reqStream = null;
4 Stream resStream = null;
5
6 try
7 {
8 byte[] data = System.Text.Encoding.Default.GetBytes(param);
9
10 //想服务器端发送请求,获取照片信息
11 myRequest = (HttpWebRequest)WebRequest.Create(url);
12 myRequest.Method = "POST";
13 myRequest.KeepAlive = true;
14 myRequest.ContentType = "application/octet-stream";
15 myRequest.ContentLength = data.Length;
16 reqStream = myRequest.GetRequestStream();
17 reqStream.Write(data, 0, data.Length);
18 reqStream.Close();
19
20 myResponse = (HttpWebResponse)myRequest.GetResponse();
21 resStream = myResponse.GetResponseStream();
22 data = new byte[512];
23 int count = 0;
24 UIFactory.zZRK_MODIForm.memStream = new MemoryStream();
25 while ((count = resStream.Read(data, 0, data.Length)) > 0)
26 {
27 UIFactory.zZRK_MODIForm.memStream.Write(data, 0, count);
28 }
29 resStream.Close();
30
31 }
32 catch
33 {
34 }
35 finally
36 {
37 if (resStream != null)
38 {
39 resStream.Close();
40 }
41 if (reqStream != null)
42 {
43 reqStream.Close();
44 }
45 if (myResponse != null)
46 {
47 myResponse.Close();
48 }
49 if (myRequest != null)
50 {
51 myRequest.Abort();
52 }
53 }

多了些什么?多了这个

1                 if (myRequest != null)
2 {
3 myRequest.Abort();
4 }
5

其实很多时候释放了Stream和Response还不够,客户端的Request还是在保持着,需要等垃圾回收器来回收,所以一般很容易阻塞,导致请求发送不出去。加上这个就是让HttpWebRequest实例在不需要的时候及时释放资源。这样可以重复使用而不会阻塞。 

 

感谢:

http://www.blogjava.net/TiGERTiAN/archive/2010/06/11/227708.html

posted @ 2011-12-26 12:10  knightluffy  阅读(377)  评论(0编辑  收藏  举报