我有一个Azure工作者角色运行,除其他功能之外,每80秒左右发出一次HTTP请求。这种情况持续发生随着我们扩大规模,它可能会产生更多的HTTP请求,所以我编写了使用BeginGetResponse,EndGetResponse和回调的代码。问题是......我们有一处内存泄漏。当这个过程运行时,它会缓慢但确定地失去记忆,直到完全耗尽为止。有时候GC会启动并释放一些未使用的对象,但它会继续缓慢下降趋势。我必须显式关闭异步HTTP请求的ResponseStream吗?
当我们的回调执行并且我们用EndGetResponse(),完成请求时,我们不会触及响应流。所有我们需要知道的是HTTP状态码,我们将其保存为我们自己的记录。我们永远不会调用GetResponseStream(),然后再调用Close()。我们做关闭()HttpWebResponse。
我的问题是:我们需要做的事情与响应流,然后关闭()它?不这样做会导致内存泄漏?我所见过的所有MS示例/其他SO讨论都与流有关。我不知道我们是否应该添加的GetResponseStream()关闭()...
下面的代码:
// the request state class, passed along with async request
public class RequestState
{
public HttpWebRequest Request { get; set; }
public HttpWebResponse Response { get; set; }
// some other properties to track which request this is..
}
...... in some other class .....
// code to perform the request
public void DoHttpRequest()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://myurl.....");
RequestState state = new RequestState(req); // this just sets the Request property on RequestState
req.BeginGetResponse(OnRequestComplete, state);
}
// the callback, request has finished
public void OnRequestComplete(IAsyncResult result)
{
RequestState state = (RequestState)result.AsyncState;
HttpWebRequest req = state.Request;
state.Response = (HttpWebResponse)req.EndGetResponse(result);
// we do not care about the body of the response
// all we want is the status code, which we store somewhere else..
if (state.Response.StatusCode == HttpStatusCode.OK || state.Response.StatusCode == HttpStatusCode.Created)
{
// comm was successful
// save this result code somewhere...
}
else if (state.Response.StatusCode == HttpStatusCode.RequestTimeout || state.Response.StatusCode == HttpStatusCode.GatewayTimeout)
{
// comm timed out
// save this result code somewhere..
}
else
{
// something else, comm failed
// save this result code somewhere..
}
// we've got the relevant data from the HttpWebResponse object, dispose of it
state.Response.Close();
}
谢谢!
最新的工具“直到它用完完全” - 你得到一个'OutOfMemoryException'? –
由于它位于Azure云上,因此我无法追踪该点的实际行为。我们的HTTP状态代码存储从80秒延长到更长时间,然后角色“降级”并完全停止运行。每10秒对角色的可用内存进行分析,表明内存趋势向下,直到达到0 ..需要几天时间。 –