2

我有一个客户端应用程序通过 UDP 或 TCP 套接字从服务器接收视频流。

最初,当它使用 .NET 2.0 编写时,代码使用 BeginReceive/EndReceive 和 IAsyncResult。客户端在它自己的窗口中显示每个视频,并使用它自己的线程与服务器通信。但是,由于客户端应该长时间处于运行状态,并且可能同时有 64 个视频流,因此每次调用数据接收回调时分配的 IAsyncResult 对象存在“内存泄漏”。

这会导致应用程序最终耗尽内存,因为 GC 无法及时处理块的释放。我使用 VS 2010 性能分析器验证了这一点。

所以我修改了代码以使用 SocketAsyncEventArgs 和 ReceiveFromAsync(UDP 案例)。但是,我仍然在以下位置看到内存块的增长:

System.Net.Sockets.Socket.ReceiveFromAsync(class System.Net.Sockets.SocketAsyncEventArgs)

我已经阅读了所有关于实现代码的示例和帖子,但仍然没有解决方案。

这是我的代码的样子:

// class data members
private byte[] m_Buffer = new byte[UInt16.MaxValue];
private SocketAsyncEventArgs m_ReadEventArgs = null;
private IPEndPoint m_EndPoint; // local endpoint from the caller

初始化

m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
m_Socket.Bind(m_EndPoint);
m_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, MAX_SOCKET_RECV_BUFFER);

//
// initalize the socket event args structure. 
//
m_ReadEventArgs = new SocketAsyncEventArgs();
m_ReadEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(readEventArgs_Completed);
m_ReadEventArgs.SetBuffer(m_Buffer, 0, m_Buffer.Length);
m_ReadEventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
m_ReadEventArgs.AcceptSocket = m_Socket;

开始读取过程:

bool waitForEvent = m_Socket.ReceiveFromAsync(m_ReadEventArgs);
if (!waitForEvent)
{
    readEventArgs_Completed(this, m_ReadEventArgs);
}

读取完成处理程序:

private void readEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
    if (e.BytesTransferred == 0 || e.SocketError != SocketError.Success)
    {
        //
        // we got error on the socket or connection was closed
        //
        Close();
        return;
     }

     try
     {
          // try to process a new video frame if enough data was read
          base.ProcessPacket(m_Buffer, e.Offset, e.BytesTransferred);
     }
     catch (Exception ex)
     {
          // log and error
     }

     bool willRaiseEvent = m_Socket.ReceiveFromAsync(e);

     if (!willRaiseEvent)
     {
         readEventArgs_Completed(this, e);
     }
}

基本上代码工作正常,我可以完美地看到视频流,但这种泄漏真的很痛苦。

我错过了什么吗???

非常感谢!!!

4

1 回答 1

1

readEventArgs_Completed而不是在!willRaiseEvent使用后递归调用goto返回到方法的顶部。我注意到当我有一个类似于你的模式时,我正在慢慢地咀嚼堆栈空间。

于 2014-08-21T18:06:38.350 回答