Cocket内存泄漏Socket.BeginSend \ Receive

时间:2014-05-03 17:02:31

标签: c# sockets memory-leaks send

所以,在我的服务器应用上遇到此问题。 我接受客户,然后开始ping他。 这里测试代码:

while (true)
{
    for (int q=0;q<100;q++)
    {
        byte[] buffer = new ServerWritePingPacket(rand).Compile(); //after Compile this class disposed success, so problem not here
        client.workSocket.BeginSend(buffer, 0, buffer.Length, 0, SendCallback, client);
    }
    Thread.Sleep(100);
}

private void SendCallback(IAsyncResult ar)
{
    Client stateClient = (Client)ar.AsyncState;
    try
    {
        int bytesSent = stateClient.workSocket.EndSend(ar);
    }
    catch (Exception e)
    {
        CloseConnection(stateClient);
    }
}

启动后,我可以看到.NET内存分析器中的内存泄漏 http://pumpshooter.com/jR30eFbz - 这是截图,在那里你可以看到1,624,296个未被遮挡 ExecutionContext对象,在调用BeginSend之后创建(这是几分钟,在几个小时之后可以是数百万+++)。

如果我注释掉BeginSend - 不创建ExecutionContext

请帮帮我。

更新#1 所以,简单的服务器(完整代码) - 它提供了巨大的内存泄漏!

class Program
{
    static Socket server;
    static byte[] readBuffer;

    static void Main(string[] args)
    {
        readBuffer = new byte[ushort.MaxValue];
        byte[] sendBuffer = new byte[] { 0x10, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
        server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345));
        server.Listen(1000); 
        server.DontFragment = true;
        Socket clientSocket = server.Accept();
        Console.WriteLine("New connection");
        while (true)
        {
            try
            {
                clientSocket.BeginSend(sendBuffer, 0, sendBuffer.Length, 0, SendCallback, clientSocket);
            }
            catch (Exception error)
            {
                Console.WriteLine(error.ToString());
            }
        }
        Console.ReadLine();
    }

    static void SendCallback(IAsyncResult ar)
    {
        Socket clientSocket = (Socket)ar.AsyncState;
        clientSocket.EndSend(ar);
    }
}

0 个答案:

没有答案