You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET连续GET请求挂起超时问题排查与解决咨询

问题原因与解决方案

核心原因

你的VB.NET代码没有正确释放HTTP请求相关资源,导致.NET默认的连接池被占满。.NET的ServicePointManager默认对每个目标服务器只允许2个并发连接,前两次请求的连接因为未被释放,一直处于占用状态,第三次请求时连接池没有可用连接,只能等待连接释放,最终触发超时。而Postman每次请求都会主动关闭连接,不会占用连接池资源,所以可以正常连续发起请求。

解决方案

使用Using语句包裹所有实现了IDisposable接口的对象(如HttpWebRequest、HttpWebResponse、StreamReader),确保这些对象在使用完成后自动释放资源,将连接归还到连接池。修改后的代码如下:

Sub Eventos(ByVal token)
    Dim responseString As String = String.Empty
    Dim jsonObject As JObject
    Dim EventosArray As JArray

    ServicePointManager.ServerCertificateValidationCallback = Function() True
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

    ' Using自动释放HttpWebRequest资源
    Using request As HttpWebRequest = CType(WebRequest.Create("https://merchant-api.ifood.com.br/order/v1.0/events:polling"), HttpWebRequest)
        request.Headers.Add("Authorization", "Bearer " & token)
        request.Method = "GET"
        request.ContentType = "application/json"
        request.Timeout = 60000

        ' Using自动释放HttpWebResponse资源
        Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
            ' Using自动释放StreamReader资源
            Using reader As New StreamReader(response.GetResponseStream())
                responseString = reader.ReadToEnd()
            End Using
        End Using
    End Using

    If Not String.IsNullOrEmpty(responseString) Then
        jsonObject = JObject.Parse("{events:" & responseString & "}")
        EventosArray = jsonObject("events")

        For Each evento As JObject In EventosArray
            Dim cleanedEvent As String = evento.ToString.Replace(vbCr, "").Replace(vbLf, "")
            Module1.ApagaEventos(cleanedEvent, token)
            
            If evento("code") = "PLC" Then
                Module1.orderId = evento("orderId")
            End If
        Next

        Console.WriteLine(jsonObject)
    End If
End Sub

额外优化建议

  • 优先通过Using语句管理资源,不推荐直接设置request.KeepAlive = False(关闭KeepAlive会增加TCP握手开销,影响性能)。
  • 检查Module1.ApagaEventos方法是否也存在资源未释放的问题,避免连锁导致连接池占用。
  • 增加异常捕获逻辑,处理请求过程中可能出现的网络异常,避免程序意外崩溃。

内容的提问来源于stack exchange,提问作者Skeff Igor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 11:03:08