小型测试应用尝试使用HttpClient与服务器通信,并指定超时。
但看起来超时永远不会中止客户端请求:
#r "System.Core.dll"
#r "System.Net.dll"
#r "System.Net.Http.dll"
#r "System.Web.dll"
#r "System.Web.Http.dll"
open System
open System.Net
open System.Net.Http
open System.Threading
open System.Web
open System.Web.Http
let listener = new HttpListener()
// https://stackoverflow.com/questions/4019466/httplistener-access-denied/4115328#4115328
// netsh http add urlacl url=http://*:7842/ user=COMPUTER\User
// netsh http show urlacl - make sure that it exists
// netsh http delete urlacl http://*:7842/ - delete it
listener.Prefixes.Add("http://*:7842/")
listener.Start()
let handler = async {
while true do
let context = listener.GetContext()
Console.WriteLine("ok")
}
let requester = async {
let client = new HttpClient()
client.Timeout <- TimeSpan.FromMilliseconds(float(1))
client.BaseAddress <- Uri("http://127.0.0.1:7842/")
try
let! result = client.GetAsync("") |> Async.AwaitTask
printf "result: %s" (string(result))
with
| _ -> printf "timeout?"
}
Async.Start(handler)
Thread.Sleep(750)
Async.Start(requester)
Thread.Sleep(100000)
此应用程序中的超时永远不会发生,这很奇怪。
更新:可能与HttpClient.GetAsync(...) never returns when using await/async
有关Update2:似乎此解决方法正在运行,但不确定它是否正确:
try
let requestTask = client.GetAsync("")
let! success = Async.AwaitIAsyncResult(requestTask, 3000)
let result = requestTask.Result
printf "result: %s" (string(result))
with
| ex -> printf "timeout? %s\n" (ex.ToString())
客户端是否应该被处置(可能不是因为它可以被重用于其他线程/任务中的其他请求)?