gpt4 book ai didi

c# - HTTP 连接问题

转载 作者:可可西里 更新时间:2023-11-01 16:39:27 25 4
gpt4 key购买 nike

我有一个大问题(抱歉我的英语不好)。我直接附上我的代码:

public bool isServerOnline()
{
Boolean ret = false;

try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(VPMacro.MacroUploader.SERVER_URL);
req.Method = "HEAD";
req.KeepAlive = false;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK)
{
// HTTP = 200 - Internet connection available, server online
ret = true;
}
resp.Close();
return ret;

}
catch (WebException we)
{
// Exception - connection not available
Log.e("InternetUtils - isServerOnline - " + we.Status);
return false;
}
}

这个函数被很多线程调用并向Tomcat服务器发送HEAD请求。因此,此方法为我执行的每个请求打开一个连接,并且在 10 分钟内我有 100 个连接处于事件状态。

如何解决这个问题?

最佳答案

您可以做 2 件事来正确管理连接:

首先:

初始化

HttpWebResponse resp;

在 try 语句之前。

然后在 finally 语句中结束

finally
{
if (resp != null)
{
resp.Close();
}
}

第二个:

尝试使用“using()”子句管理您的连接

using(var a = new connection())
{
//Your code
}

关于c# - HTTP 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6263372/

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