我知道,這裏已經有很多類似的問題,但我沒有找到一個解決方案,使其更快或者它如此緩慢的原因?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