工作需要,用到了c#輪訓發(fā)騰訊IM服務端消息功能,因為消息量比較大,而且要在盡可能短的時間內(nèi)都發(fā)送完成,開始的時候用了定時器,每一秒輪訓一次,經(jīng)過測試,發(fā)現(xiàn)1秒內(nèi)只能成功發(fā)送5條左右,因為是排隊。
按照這個速度,如果有1000條消息,則需要200秒,差不多3分多鐘才能發(fā)送完,無法接受,嘗試用異步,多線程,線程池,Task,發(fā)現(xiàn)也只是快了1半的時間,沒有達到多線程想象中的效果,感覺還是在排隊。
把程序中發(fā)送消息的功能注釋掉,換成Thread.Sleep(1000),發(fā)現(xiàn)多線程有效,問題就出在http請求這塊,后來終于查到資料HttpRequest有個限制并發(fā)數(shù)。
百度了一下,發(fā)現(xiàn)了個文章[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秒之間了,這樣看著就比較正常了。。