WebRequest多线程 超时问题

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.Net.NetworkInformation;
public class ThreadDemo
{
    public static void Main()
    {
        List<Thread> tls = new List<Thread>();
        System.Net.ServicePointManager.DefaultConnectionLimit = 20;//最大并发数,.net默认并发只有2个
        for (int i = 0; i < 50; i++)
        {
            tls.Add(new Thread(new ThreadStart(test)));
            tls[i].Name = "线程" + (i + 1);
            tls[i].Start();
        }
    }
    public static void test()
    {
        new RequestTest().GetRequest(Thread.CurrentThread.Name, "http://163.com");
    }
}

public class RequestTest
{
    System.Net.HttpWebRequest httpReq = null;
    System.Net.HttpWebResponse httpRes = null;
    /// <summary>
    /// 通过WebRequest来访问网址,网址必须包含http:或https:      
    /// </summary>  
    /// <param name="threadName">当前线程</param>     
    /// <param name="url">要访问的网址</param>
    public void GetRequest(string threadName, string url)
    {
        if (string.IsNullOrEmpty(url) || url.Length <= 0) return;
        DateTime dt = DateTime.Now;
        if (!url.Contains("."))
        {
            return;
        }
        if (!url.Contains("http://") && !url.Contains("https://"))
            url = "http://" + url;
        try
        {
            httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Proxy = null;//不使用代理 .NET4.0中的默认代理是开启的
            httpReq.KeepAlive = false;//不建立持久性连接
            httpReq.Timeout = 5000;//连接网址的超时时间
            httpReq.ReadWriteTimeout = 5000;//读取网址内容的超时时间               
            httpRes = (HttpWebResponse)httpReq.GetResponse();
            Console.WriteLine(threadName + "  " + url + ":" + httpRes.StatusCode);
        }
        catch (Exception e)
        {
            Console.WriteLine(threadName + "  " + url + " Error:" + e.Message);
        }
        finally
        {
            if (httpRes != null)
            {
                httpRes.Close();//关闭连接
            }
            if (httpReq != null)
            {
                httpReq.Abort();//中止请求
            }
            httpReq = null;
            httpRes = null;
            System.GC.Collect();//强制垃圾回收,并释放资源
        }
    }
}

参考:

http://www.cnblogs.com/i80386/archive/2013/01/11/2856490.html

DefaultConnectionLimit 并发

http://blogs.msdn.com/b/wenlong/archive/2009/02/08/why-only-two-concurrent-requests-for-load-testing.aspx

Proxy

http://stackoverflow.com/questions/7325572/c-webrequest-proxy-null-side-effects

http://blog.sina.com.cn/s/blog_5fc933730100w3xz.html

原文地址:https://www.cnblogs.com/huangtailang/p/3180651.html