Search code examples
c#filememoryallocationtransfer

How do I reduce the memory usage in this c# File Transfer?


I have a simple file transfer app written in c# using TCP to send the data.

This is how I send files:

Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


        byte[] fileName = Encoding.UTF8.GetBytes(fName); //file name
        byte[] fileData =  new byte[1000*1024];
        byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //length of file name
        FileStream fs = new FileStream(textBox1.Text, FileMode.Open);            
        try
        {
            clientData = new byte[4 + fileName.Length];
        }
        catch (OutOfMemoryException exc)
        {
            MessageBox.Show("Out of memory");
            return;
        }

        fileNameLen.CopyTo(clientData, 0);
        fileName.CopyTo(clientData, 4);
        clientSock.Connect("172.16.12.91", 9050);
        clientSock.Send(clientData, 0, clientData.Length, SocketFlags.None);                       
        progressBar1.Maximum = (int)fs.Length;
        while (true)
        {
            int index = 0;
            while (index < fs.Length)
            {
                int bytesRead = fs.Read(fileData, index, fileData.Length - index);
                if (bytesRead == 0)
                {
                    break;
                }

                index += bytesRead;
            }
            if (index != 0)
            {
                clientSock.Send(fileData, index, SocketFlags.None);
                if ((progressBar1.Value + (1024 * 1000)) > fs.Length)
                {
                    progressBar1.Value += ((int)fs.Length - progressBar1.Value);
                }
                else
                    progressBar1.Value += (1024 * 1000);
            }

            if (index != fileData.Length)
            {
                progressBar1.Value = 0;
                clientSock.Close();
                fs.Close();

                break;

            } 
        }            

    }

In taskmanager,the Release version of this app's memory usage goes 13 MB when I use the OpenFileDialog, then goes up to 16 MB when it sends data then stays there. Is there anything I can do to reduce the memory usage? Or is there a good tool that I can use to monitor the total allocation memory in the app?

And while we're there, is 16 MB really that high?


Solution

  • 16MB doesn't sound that much of memory usage. You could use the inbuilt visual studio profiler to see what's costing the most performance. See link below for more information about the profiler: http://blogs.msdn.com/b/profiler/archive/2009/06/10/write-faster-code-with-vs-2010-profiler.aspx