我知道,这里已经有很多类似的问题,但我没有找到一个解决方案,使其更快或者它如此缓慢的原因?NetworkStream.Read为什么这么慢?
我们在C#.NET中有一个应用程序,需要通过TCP与在同一个TCP流上回答的设备进行通信(全部以字节为单位)。发送消息的速度非常快(约20毫秒),但是当我们使用NetworkStream.Read()方法(或类似的Socket.Receive())从TCP套接字读取数据时,大约需要600ms。通过在Read方法之前启动秒表并在Read之后立即停止它,我可以得到这个数字。
我也使用Wireshark记录流量,在那里我看到通信非常快(使用TCPNoDelay和TCPAckFrequency注册表攻击),但在那里我看到以下发送到设备的消息是在600毫秒后阅读前面的答案)。
设备不能同时处理多个消息,他们也回答一个自定义的确认,以便我们的程序知道最后发送的消息被接收并构建正确。
好的,这里有一些测试代码,我有一个控制台应用程序,甚至有600毫秒延迟阅读的问题。
try
{
if (!retry)
{
Console.WriteLine("Please enter the IP address you want to check:");
ip = Console.ReadLine();
Console.WriteLine("Please enter the port where you want to check on:");
port = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Connecting to {0}: {1}", ip, port);
Console.WriteLine("Please enter the message you want to write to the specified port:");
message = Console.ReadLine();
}
tcp = new TcpClient(ip, port);
tcp.NoDelay = true;
tcp.Client.NoDelay = true;
Stopwatch sWrite = new Stopwatch();
Stopwatch sRead = new Stopwatch();
Stopwatch sDataAvailable = new Stopwatch();
using (NetworkStream ns = tcp.GetStream())
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message + "\r");
sWrite.Start();
ns.Write(data, 0, data.Length);
sWrite.Stop();
data = new byte[256];
sRead.Start();
Console.WriteLine("There is data on the socket: {0}", ns.DataAvailable);
int readBytes = ns.Read(data, 0, data.Length);
sRead.Stop();
message = System.Text.Encoding.ASCII.GetString(data, 0, readBytes);
Console.WriteLine(message);
}
Console.WriteLine("The reading speed is {0} and the writing speed is {1}", sRead.ElapsedMilliseconds, sWrite.ElapsedMilliseconds);
}
catch { }
finally
{
tcp.Close();
}
这提供了以下结果:The reading speed is 500 and the writing speed is 0
没有一行代码? – TomTom 2012-03-13 10:35:07
mybe是缓慢写入流的设备? – 2012-03-13 10:36:17
我认真地怀疑你会通过查看流阅读代码来找到它。关注程序的其余部分,尤其是启动线程池线程的任何代码。一个快速测试是调用ThreadPool.SetMinThreads()并传递一个大数字。 – 2012-03-13 11:39:06