Multi-Thread WebRequest : Timeout
In test web, there are 4 links at index page. When I run my program, I can’t get all of them contents. Sometimes I can successed, but always not. In the fail state, I can get the first page right content; sometimes can get second page content. The error message is: timeout. The code is like following:
1

2


10

11

12


19

20

21


At the DoSomeThing () method, I get the page content and then call the service method to add the date to server. When I comment the UpLoadDataToService (), it run ok. I can get all of 4 pages contents rightly. I thought it may caused by the spending of upload data. So, I try to set the WebRequest timeout to longer, but the problem is still.
I don’t know where is wrong. Finally, I solve this problem like the following codes. It takes me much time.

2

3

4

5

6

7

8

I don’t know what the difference between these is. So I google it. At last I got it. The reason is that: single-user client SHOULD NOT maintain more than 2 connections with any server or proxy.
Its means the default limit connection is 2. We can solve this problem by these:
ServicePointManager.DefaultConnectionLimit = 100;
So when I call the service method it takes some seconds. The WebRequst can’t release quickly. When I create the third WebRequest, it’ll throw an error: timeout.
Let’s see what the difference between my two solutions above is right now. I put out some info to see what’s happen. I find that, if I use the ThreadPool.QueueUserWorkItem(DoSomeThing, response);
The response.Close (); will reached soon, needn’t waiting for DosomeThing () finished. There are no three WebRequest send request at the same times, so it will works ok, How Fun!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步