我有一个小应用程序从代理商接收数千个数据并将这些数据上传到另一个服务器,来自代理的数据非常小,通常是10KB但是代理写入速度非常快,所以我的应用程序有一个内部4M缓冲区,一次缓冲区已满,它会创建一个新的4M缓冲区,并将旧缓冲区传递给任务以执行HTTP上载。像这样的代码:
lock (Locker)
{
if (input.Length > this.buffer.Length - this.bufferDataLen)
{
// Save the current buffer and create a new one.
// We should release locker as fast as we can.
byte[] tempBuffer = this.buffer;
int oldBufferDataLen = this.bufferDataLen;
this.buffer = new byte[tempBuffer.Length]; // save size buffer, 4MB
this.bufferDataLen = 0;
Task.Factory.StartNew(
() =>
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this._uploadUrl);
request.Method = "POST";
request.ContentType = this._contentType;
request.ContentLength = oldBufferDataLen;
request.KeepAlive = false;
request.Proxy = null;
UploaderState state = new UploaderState(tempBuffer, oldBufferDataLen, request);
IAsyncResult result = request.BeginGetRequestStream(this.OnGetRequestStreamComplete, state);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, this.TimeoutCallback, state, this._timeoutMs, true);
});
}
// Copy incoming data to either old buffer or new buffer
Buffer.BlockCopy(input.Buffer, 0, this.buffer, this.bufferDataLen, input.Length);
this.bufferDataLen += input.Length;
}
我希望GC能正确处理tempBuffer。但是,当我运行我的应用程序时,我注意到应用程序的内存使用量增加得非常快,从内存转储中,托管堆上有305个字节[]对象,总大小为469,339,928 B,包含大小为469,339,928 B,当应用程序只运行几分钟时捕获转储。
我的问题是为什么GC没有释放那些byte []?我应该明确调用GC.Collect吗?在我的情况下,我应该自己管理缓冲池吗?