WebRequest多线程 超时问题
2024-08-27 04:06:17
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 = ;//最大并发数,.net默认并发只有2个
for (int i = ; i < ; i++)
{
tls.Add(new Thread(new ThreadStart(test)));
tls[i].Name = "线程" + (i + );
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 <= ) 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 = ;//连接网址的超时时间
httpReq.ReadWriteTimeout = ;//读取网址内容的超时时间
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 并发
Proxy
http://stackoverflow.com/questions/7325572/c-webrequest-proxy-null-side-effects
http://blog.sina.com.cn/s/blog_5fc933730100w3xz.html
最新文章
- JS:event对象下的target属性和取消冒泡事件
- HTML锁定Table中某一列
- BPM到底能做什么?K2为你解读
- 支持https请求以及https请求的抓包
- centos下的lnmp环境搭建
- 学c语言做练习之文件
- 一次$.getJSON不执行的记录
- regsvr32 命令小集注册OCX控件,注册控件(包括十几个举例)
- notify丢失、虚假唤醒
- LinkedList 实现 Queue
- java多线程快速入门(八)
- System.Web.UI.Page的页面基类
- PHP企业微信授权
- 中式台球 规则 ( ChinaBilliards )
- 页面元素固定在页面底部的纯css代码(兼容IE6)
- Exp5
- Locust性能测试5-参数化批量注册
- 6-查看centos中的用户和用户组
- 【BZOJ4912】天才黑客(最短路,虚树)
- java开发中的诡异事件
热门文章
- python opencv3 基于ORB的特征检测和 BF暴力匹配 knn匹配 flann匹配
- Linux下使用thrfit
- [CC-SUBWAY]Subway Ride
- 【ACM-ICPC 2018 徐州赛区网络预赛】E. End Fantasy VIX 血辣 (矩阵运算的推广)
- Python环境右键定制
- python开发_xml.dom_解析XML文档_完整版_博主推荐
- Codeforces Round #354 (Div. 2) C. Vasya and String 二分
- POJ 2356 Find a multiple 抽屉原理
- 简单的文件上传html+ashx
- flex socket policy