在多线程环境下使用HttpWebRequest或者调用Web Service

最近使用多线程同时调用一个Web Service,总是有很多调用报超时,代码类似于下面的代码(为了简化,我把调用Web Service改为使用HttpWebRequest访问一个网址,效果时一样的):

我循环调用100次,但是总是有几十次调用报超时,具体如下:

System.Net.WebException: 操作已超时。
   at System.Net.HttpWebRequest.GetResponse()
   at HttpRequestTest.HttpRequestTest.MakeWebRequest(Object obj) in g:\my documents\visual studio projects\httprequesttest\httprequesttest.cs:line 35

真的不知道为什么,难道Web Service就不能在多线程的环境下调用!

因为目前找不到原因,暂时放在首页,想向各位请教,明天就撤调,请手下留情,谢谢!


 1 using  System;
 2 using  System.Diagnostics;
 3 using  System.Net;
 4 using  System.Threading;
 5
 6 namespace  HttpRequestTest
 7 {
 8    /**//// <summary>
 9    /// Class1 的摘要说明。
10    /// </summary>

11    class HttpRequestTest
12    {
13
14        //[STAThread]
15        static void Main(string[] args)
16        {
17            for(int i = 0; i < 100; i++ )
18            {
19                ThreadPool.QueueUserWorkItem(new WaitCallback(MakeWebRequest),"http://www.163.com");
20            }

21            Console.ReadLine();
22        }

23
24        private static void MakeWebRequest (object obj)
25        {
26            string url = obj as string;
27            HttpWebResponse res = null;
28            try
29            {
30                HttpWebRequest req = (HttpWebRequest)WebRequest.Create (url);
31                req.Timeout = 15000;
32
33                Console.WriteLine ("\nConnecting to " + url + " ");
34
35                res = (HttpWebResponse)req.GetResponse ();
36
37                Console.WriteLine("[" + AppDomain.GetCurrentThreadId() + "] ContentLength:" + res.ContentLength);
38                Console.WriteLine ("Connected.\n");
39
40
41            }

42            catch (Exception e)
43            {
44                Console.WriteLine ("Source : " + e.Source);
45                Console.WriteLine ("Message : " + e.Message);
46                Console.WriteLine(e.ToString());
47                Debug.WriteLine(e.ToString());
48                //Console.WriteLine("StackTrace :" + e.StackTrace);
49            }

50            finally
51            {
52                if (res != null)
53                {
54                    res.Close ();
55                }

56            }

57        }

58    }

59}

转载于:https://www.cnblogs.com/lanru/archive/2010/10/15/1852212.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值