在多線程環境下使用HttpWebRequest或者調用Web Service

來源:互聯網
上載者:User
最近使用多線程同時調用一個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就不能在多線程的環境下調用!

因為目前找不到原因,暫時放在首頁,想向各位請教,明天就撤調,請手下留情,謝謝!

 1using System;
 2using System.Diagnostics;
 3using System.Net;
 4using System.Threading;
 5
 6namespace 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}
60

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.