工作需要,用到了c#轮训发腾讯IM服务端消息功能,因为消息量比较大,而且要在尽可能短的时间内都发送完成,开始的时候用了定时器,每一秒轮训一次,经过测试,发现1秒内只能成功发送5条左右,因为是排队。
按照这个速度,如果有1000条消息,则需要200秒,差不多3分多钟才能发送完,无法接受,尝试用异步,多线程,线程池,Task,发现也只是快了1半的时间,没有达到多线程想象中的效果,感觉还是在排队。
把程序中发送消息的功能注释掉,换成Thread.Sleep(1000),发现多线程有效,问题就出在http请求这块,后来终于查到资料HttpRequest有个限制并发数。
百度了一下,发现了个文章[Timeouts When Making Web Requests in .NET]
里面写到:
Each time you create a request, there is a System.Net.ServicePoint assigned to it. ServicePoint then tries to find a connection which will serve a given request. Each write and read operation on a connection is performed by a ConnectStream instance. Connections are pooled and their number is by default limited to two connections per IP address. You may configure the maximum number of connections per IP address or DNS name in the application configuration file (section http://system.net\connectionManagement\add), e.g.:
<configuration> <system.net> <connectionManagement> <add address = "http://www.wg.net.pl" maxconnection = "4" /> <add address = "*" maxconnection = "2" /> </connectionManagement> </system.net> </configuration>
原来是这个锅,默认最多一个地址只能有两个connection,怪不得如此。。
改成100个,可以到3.x到4秒之间了,这样看着就比较正常了。。