WebRequest线程在两个请求时阻塞

时间:2011-08-19 14:21:10

标签: multithreading post console webrequest

我需要测试数据上下文并查看它在多个同时请求下的行为,因为我创建了一个简单的控制台应用程序[理论上]将发送这些请求:

private static DateTime startTime = DateTime.Now.AddSeconds(5);
public static Random rand = new Random();

static void Main(string[] args)
{
    const byte testThreads = 10;

    ThreadStart[] threadStarts = new ThreadStart[testThreads];
    Thread[] threads = new Thread[testThreads];

    for (byte i = 0; i < testThreads; i++)
    {
        threadStarts[i] = new ThreadStart(ExecutePOST);
        threads[i] = new Thread(threadStarts[i]);
    }

    for (byte i = 0; i < testThreads; i++){ threads[i].Start(); }

    for (byte i = 0; i < testThreads; i++){ threads[i].Join(); }
}

被调用的函数是

private static void ExecutePOST()
{
    while (DateTime.Now < startTime) { }

    Console.WriteLine("{0} STARTING TEST", DateTime.Now.Millisecond);
    WebRequest webRequest = WebRequest.Create(/*URL*/);
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.Method = "POST";

    string name = string.Format("Test {0}", Program.rand.Next(1000));

    byte[] bytes = Encoding.ASCII.GetBytes(/*PARAMETERS*/);
    Stream output = null;
    try
    {
        webRequest.ContentLength = bytes.Length;
        output = webRequest.GetRequestStream();
        output.Write(bytes, 0, bytes.Length);

        Console.WriteLine("{0}:{1}", DateTime.Now.Millisecond, name);
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        if (output != null)
        {
            output.Close();
        }
    }
}

我得到的输出是: Output

有人可以解释一下这种行为吗?为什么在两次请求后停止?

谢谢

1 个答案:

答案 0 :(得分:3)

是的,这是因为默认情况下,每个网址的连接数限制为2 - 这些连接是合并的。

您通过将数据写入请求流来占用连接,但从未获得响应。一个简单的:

using (webRequest.GetResponse()) {}
该方法结束时的

可能会将其排除。这将完成请求并释放连接以供另一个请求使用。

另请注意,输出流的using语句也会使您的代码更简单。