Ruben

Ruben

  • NA
  • 3
  • 13.1k

Async network io leaking memory?

Jan 9 2011 10:45 AM
Hi,

I've written a little test programm that uses two TcpClients to send and receive data to/from itself. I'm using asynchronous Io with BeginXXX/EndXXX Methods and callbacks.  I've removed everything that distracts from what is actually going on (exception handling, clean termination etc.). Code was compiled with Vs2008 targeting .Net3.5.

When running the programm the amount of used memory continously increases (observed in the taskmanger) no matter if the Release or Debug build is used.  What is going wrong here? Am I blind? Any insight is appretiated.

(Please abstain from suggesting different code with excplicit callback methods, sync Io or anything. I'm just intrested in understanding what is leaking memory in my example and not what would make the code more readable or more beautiful in someones personal opinion.)

Thanks in advance,
 Ruben

        static void Main(string[] args)
        {
            AutoResetEvent evRead = new AutoResetEvent(false);

            // sender
            var thSend = new Thread
            (
                () =>
                {
                    TcpClient sender = new TcpClient();
                    sender.Connect(IPAddress.Loopback, 1000);
                    byte[] buf = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    AsyncCallback cbSend = null;
                    cbSend = (resSend) =>
                    {
                        sender.GetStream().EndWrite(resSend);
                        Console.WriteLine("written");
                       
                        // continue writing when reading was done
                        evRead.WaitOne();
                        sender.GetStream().BeginWrite(buf, 0, buf.Length, cbSend, null);
                    };

                    // intiate writing
                    sender.GetStream().BeginWrite(buf, 0, buf.Length, cbSend, null);
                }
            );

            // setup connection reader <-> sender
            TcpListener listener = new TcpListener(IPAddress.Any, 1000);
            listener.Start();
            thSend.Start();
            TcpClient reader = listener.AcceptTcpClient();

            // reader
            byte[] bufRead = new Byte[20];
            AsyncCallback cbRead = null;
            cbRead = (resRead) =>
            {
                int nRead = reader.GetStream().EndRead(resRead);
                evRead.Set();

                //for (int i = 0; i < nRead; i++) Console.WriteLine(bufRead[i]);
                Console.WriteLine("read");

                // continue reading
                reader.GetStream().BeginRead(bufRead, 0, bufRead.Length, cbRead, null);
            };

            // initiate reading
            reader.GetStream().BeginRead(bufRead, 0, bufRead.Length, cbRead, null);

            Console.ReadLine();
        }


Answers (2)