[英]How do I reduce the memory usage in this c# File Transfer?
我有一个使用c#编写的简单文件传输应用程序,使用TCP发送数据。
这是我发送文件的方式:
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;
}
}
}
在taskmanager中,当我使用OpenFileDialog时,此应用程序的内存使用的发行版变为13 MB,然后在发送数据然后停留在该位置时达到16 MB。 我有什么办法可以减少内存使用量? 还是有一个很好的工具可以用来监视应用程序中的总分配内存?
当我们在那里时,16 MB真的那么高吗?
16MB听起来并没有那么多的内存使用情况。 您可以使用内置的Visual Studio Profiler来查看花费最大的性能。 有关探查器的更多信息,请参见下面的链接: http : //blogs.msdn.com/b/profiler/archive/2009/06/10/write-faster-code-with-vs-2010-profiler.aspx
我注意到,当我最小化任何应用程序时,内存使用量都会大大下降。 我最终找到了一种以编程方式复制此效果的方法,这就是我发现的结果:
[DllImport("kernel32.dll")]
public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
public void ReleaseMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
我不知道使用此方法的弊端,但到目前为止,它至少可以节省13MB的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.