gpt4 book ai didi

c# - 关闭 HttpWebRequest 以释放资源

转载 作者:行者123 更新时间:2023-11-30 14:28:28 25 4
gpt4 key购买 nike

我正在用 C# 创建 HTTP WebRequests 来浏览网站。我创建请求,获得响应并将其读入 StreamReader。然后我使用相同的请求变量来创建一个新的请求并获得一个新的响应...

下面是我的代码:

HttpWebRequest request;
WebResponse response;
Stream responseStream;
StreamReader reader;
string responseFromServer;

request = (HttpWebRequest)WebRequest.Create("https://www.firstRequest.com");

//set cookies and headers here...

response = request.GetResponse();

responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
responseFromServer = reader.ReadToEnd();


//second request using the same variables
request = (HttpWebRequest)WebRequest.Create("https://www.secondRequest.com");
response = request.GetResponse();

responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
responseFromServer = reader.ReadToEnd();

我知道我必须关闭响应、流和流读取器以释放资源。我是否必须在每个请求之间或仅在所有请求结束时执行此操作?

最佳答案

是的,你每次都需要清理自己。只需使用您忽略的 IDisposable 功能:

所以,相反,你可以

using(response = request.GetResponse())
{
using(responseStream = response.GetResponseStream())
{
using(reader = new StreamReader(responseStream))
{
responseFromServer = reader.ReadToEnd();
}
}
}

或更简洁:

using(response = request.GetResponse())
using(responseStream = response.GetResponseStream())
using(reader = new StreamReader(responseStream))
{
responseFromServer = reader.ReadToEnd();
}

...现在您无需担心调用Close。 IDisposable 实现会为您处理(当 using block 结束时)。

关于c# - 关闭 HttpWebRequest 以释放资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652419/

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