多个HttpWebRequest被延迟

时间:2012-11-07 16:57:06

标签: httpwebrequest

我想测试一个带有多个并发调用的Web服务,所以我编写了一个测试程序,它启动了100个线程,每个线程在Web服务中调用相同的方法。所有线程同时启动,但Web服务接收延迟半秒的每个请求。我可以通过调试Web服务来看到这一点,如果我运行Fiddler,我可以在HTTP调用中看到这种延迟。

我已经将ServicePointManager的DefaultConnectionLimit设置得足够高,并尝试更改其UseNagleAlgorithm和Expect100Continue设置但这些没有帮助。任何人都可以告诉我为什么当我同时请求时,HTTP调用似乎被推迟了?

这是我的代码:

using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;

namespace ConsoleApplication1
{
    class Data
    {
        public Data(CountdownEvent cde, int number)
        {
            Cde = cde;
            Number = number;
        }

        public CountdownEvent Cde { get; private set; }
        public int Number { get; private set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int numThreads = 100;
            var cde = new CountdownEvent(numThreads);

            // controls number of concurrent http connections
            ServicePointManager.DefaultConnectionLimit = numThreads;

            var sw = new Stopwatch();
            sw.Start();

            // start the threads
            for (int i = 0; i < numThreads; i++)
            {
                var t = new Thread(CallWebService);
                t.Start(new Data(cde, i + 1));
            }

            // wait for all the threads to finish
            cde.Wait();

            sw.Stop();

            Console.WriteLine(string.Format("Finished in {0} milliseconds", sw.ElapsedMilliseconds));
        }

        private static void CallWebService(object state)
        {
            var data = (Data)state;

            Console.WriteLine(string.Format("Thread {0} starting at {1}", data.Number, DateTime.Now.ToLongTimeString() + "." + DateTime.Now.Millisecond));

            var sw = new Stopwatch();
            sw.Start();

            var request = (HttpWebRequest)WebRequest.Create("http://mywebservice/test");
            request.Method = "GET";

            string result;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }

            sw.Stop();

            Console.WriteLine(string.Format("Thread {0} finishing at {1}, took {2} milliseconds", data.Number, DateTime.Now.ToLongTimeString() + "." + DateTime.Now.Millisecond, sw.ElapsedMilliseconds));

            data.Cde.Signal();
        }
    }
}

0 个答案:

没有答案