[英]NetworkStream Read Extremely Slow
我正在使用C# NetworkStream
讀取/寫入IP地址(而不是DNS地址)。
我的程序正在替換大型機上非常老的匯編語言程序。 現在在Windows上。
我正在寫/讀少於200
個字節。 字符串以LineFeed
字符結尾,因此我在Stream.Write()
之后使用StreamReader.Readline()
讀取響應。 在IBM上,寫/讀周期花費300ms
。
現在大約每2或3次讀取后,讀取就需要15
秒。 當我閱讀發送者的日志時,它在不到一秒鍾的時間內發送了數據。 由於某種原因,我得到了這15
秒的延遲。
我對正在發生的事情一無所知。
ps我注意到,如果我將流讀取超時設置為4秒,那么它會超時約4秒,這是我注意到的一件奇怪的事情。 如果我將超時設置為10秒或不設置超時,則它將在15秒后超時。
TcpClient tcpc = null;
NetworkStream stream = null;
StreamReader sr = null;
tcpc = new TcpClient();
tcpc.NoDelay = true;
tcpc.ExclusiveAddressUse = false;
tcpc.Connect("172.18.10.100", 4004);
stream = tcpc.GetStream();
sr = new StreamReader(stream, Encoding.ASCII);
sr.Peek();
string Message = null;
Message = "IX3543543" + '\r';
stream.Write(Encoding.ASCII.GetBytes(Message), 0, Message.Length);
string readmsg = null;
for (int i = 0; i < 4; i++)
readmsg = sr.ReadLine();
由於代碼永遠不會釋放IDisposable
資源,因此您的連接保持打開狀態。
using
結構,您的代碼應該運行得更快。 ReadToEnd
消息,並在釋放資源后ReadToEnd
檢查。 因此您的代碼可能如下所示:
string response = null;
using(var tcpc = new TcpClient())
{
tcpc.NoDelay = true;
tcpc.ExclusiveAddressUse = false;
tcpc.Connect("172.18.10.100", 4004);
using (var stream = tcpc.GetStream())
using (var sr = new StreamReader(stream, Encoding.ASCII))
{
sr.Peek();
var Message = "IX3543543" + '\r';
stream.Write(Encoding.ASCII.GetBytes(Message), 0, Message.Length);
response = sr.ReadToEnd();
}
}
// examine message here
var lines = response.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.