我的目标(在我扩展它之前)是每秒启动一次异步任务(在这种情况下,获取URL)。这个想法是,如果Async任务需要3秒,它的行为将如下:
0sec: Start thread 0
1sec: Start thread 1
2sec: Start thread 2
3sec: Start thread 3
3sec: Finish thread 0
4sec: Start thread 4
4sec: Finish thread 1
到目前为止,这是我的代码。添加了workTime和Async.Sleep代码以使我的问题更加明显。
let FetchUrlAsync (thread: int) (url: string) =
async {
let req = WebRequest.Create(url)
let! resp = req.AsyncGetResponse()
use stream = resp.GetResponseStream()
use reader = new System.IO.StreamReader(stream)
let workTime = System.Random().Next(5000,8000)
sprintf "start work %i" thread |> Console.WriteLine
do! Async.Sleep workTime
sprintf "end work %i (time taken: %i)" thread workTime |> Console.WriteLine
return reader.ReadToEnd()
}
Seq.initInfinite(fun i -> FetchUrlAsync i "http://www.google.com"
|> Async.StartAsTask
|> ignore
Thread.Sleep 1000
)
|> Seq.iter(id)
问题是似乎最多同时运行两个线程。为什么会这样,我做错了什么?
此外,这是我第一次使用异步做任何事情。如果你看到任何方法来改进我的代码,请告诉我(使用Thread.Sleep在这里做正确的事情吗?)
答案 0 :(得分:4)
问题是id mystring
1, (1:a,10:b,100:c,1000:f),(1:a,20:d,200:g)
2, (2:e,30:h,300:i),(2:j,40:k)
3, (3:l)
默认情况下设置为2.在您的请求之前使用类似的内容将其值提高:
System.Net.ServicePointManager.DefaultConnectionLimit