gpt4 book ai didi

asynchronous - 如何在 F# Async.Parallel 中处理 HttpWebRequest 超时

转载 作者:行者123 更新时间:2023-12-04 07:58:46 24 4
gpt4 key购买 nike

我只是花了很长时间才弄清楚为什么这段代码对于某些网址“挂起”:

let getImage (imageUrl:string) =
async {
try
let req = WebRequest.Create(imageUrl) :?> HttpWebRequest
req.UserAgent <- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
req.Method <- "GET";
req.AllowAutoRedirect <- true;
req.MaximumAutomaticRedirections <- 4;
req.Timeout <- 3000; //HAHAHA, nice try!
let! response1 = req.AsyncGetResponse()
let response = response1 :?> HttpWebResponse
use stream = response.GetResponseStream()
let ms = new MemoryStream()
let bytesRead = ref 1
let buffer = Array.create 0x1000 0uy
while !bytesRead > 0 do
bytesRead := stream.Read(buffer, 0, buffer.Length)
ms.Write(buffer, 0, !bytesRead)
return SuccessfulDownload(imageUrl, ms.ToArray())

with
ex -> return FailedDownload(imageUrl, ex.Message)
}

在设法追踪 3000 个 URL 中的哪个被挂起后,我了解到 AsyncGetResponse不注意 HttpWebRequest.Timeout .我做了一些搜索,提出了将异步请求包装在带有计时器的线程中的建议。这对 C# 来说很棒,但如果我通过 Async.Parallel |> Async.RunSynchronously 运行其中的 3000 个,处理这个问题的最佳方法是什么?

最佳答案

我只是粗略地测试了这个,但它应该有正确的行为:

type System.Net.WebRequest with
member req.AsyncGetResponseWithTimeout () =
let impl = async {
let iar = req.BeginGetResponse (null, null)
let! success = Async.AwaitIAsyncResult (iar, req.Timeout)
return if success then req.EndGetResponse iar
else req.Abort ()
raise (System.Net.WebException "The operation has timed out") }
Async.TryCancelled (impl, fun _ -> req.Abort ())

在您的代码中,调用 req.AsyncGetResponseWithTimeout()而不是 req.AsyncGetResponse() .

关于asynchronous - 如何在 F# Async.Parallel 中处理 HttpWebRequest 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5713330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com