我使用Socket
类将字节数组中的图像数据发送到在同一台PC上运行的第三方程序(所以我不必担心连接问题)。由于我的应用非常简单,因此我只使用同步send(bytes)
函数,仅此而已。问题是,它运行速度很慢。如果我发送一张20kB的小图片,它需要接近15ms,但是如果图片足够大--1.5mB,则需要接近800ms,这对我来说是不可接受的。我该如何提高插座性能?C#Socket.send非常慢
Socket sender = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 3998);
sender.Connect(remoteEP);
byte[] imgBytes;
MemoryStream ms = new MemoryStream();
Image img = Image.FromFile("С:\img.bmp");
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
imgBytes = ms.ToArray();
/*Some byte operations there: adding headers, file description and other stuff.
They are really fast and add just 10-30 bytes to array, so I don't post them*/
DateTime baseDate = DateTime.Now; // Countdown start
for (uint i = 0; i < 100; i++) sender.Send(byteMsg);
TimeSpan diff = DateTime.Now - baseDate;
Debug.Print("End: " + diff.TotalMilliseconds);
// 77561 for 1.42mB image, 20209 for 365kb, 1036 for 22kB.
你可以显示你发送图像的方式吗? – mxmissile
更新了我的文章。 – JustLogin
你是基准吗?那就是,只有'sender.Send'? – Martijn