我看到一個問題,我有一個UDP客戶端&服務器頻繁交換消息和兩個實體的內存使用量在約8K每秒速率(最終增加althoughly,這取決於它們之間的通信速率),如任務管理器中所觀察到的。.NET UDP套接字發送增加內存使用
要儘可能簡單地說明這一點,我創建基於MSDN使用UDP服務http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx樣本。
服務器:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPListener
{
private const int listenPort = 11000;
private static void StartListener()
{
bool done = false;
UInt32 count = 0;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Loopback, listenPort);
try
{
while (!done)
{
byte[] bytes = listener.Receive(ref groupEP);
if ("last packet" == System.Text.Encoding.UTF8.GetString(bytes))
{
done = true;
Console.WriteLine("Done! - rx packet count: " + Convert.ToString(count));
}
else
{
count++;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
public static int Main()
{
StartListener();
return 0;
}
}
而且客戶端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace UDPSender
{
class Program
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse(IPAddress.Loopback.ToString());
byte[] sendbuf = Encoding.ASCII.GetBytes("test string");
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
for (int i = 0; i < 500; i++)
{
s.SendTo(sendbuf, ep);
System.Threading.Thread.Sleep(50);
}
s.SendTo(Encoding.ASCII.GetBytes("last packet"), ep);
s.Dispose();
}
}
}
我都直接使用Socket接口和UDPClient,每次傳輸後丟棄客戶端套接字嘗試,明確的GC.Collect等無濟於事。
任何想法是怎麼回事 - 我不敢相信這是.NET的一個根本問題,必須有我的代碼/樣品問題....
@rw:不要使用任務管理器來查看內存使用。使用Perfmon(自帶Windows)或類似Sysinternals的Process Explorer並監控'專用字節'度量值。 – Andy
@安迪:任務管理器中的「虛擬內存大小」列與「專用字節」相同。 –
@rw:在運行完所有的rx/tx之後,你是否可以睡眠一段時間,以確保它們已經發送了所有未完成的軟件包,然後使用內存使用? –