我正在从处于 while 循环中的 NetworkStream 读取数据。问题是我看到 100% 的 CPU 使用率。有没有办法阻止这种情况发生?
这是我到目前为止所拥有的:
while (client != null && client.Connected)
{
NetworkStream stream = client.GetStream();
data = null;
try
{
// Check if we are still connected.
if (client.Client.Poll(0, SelectMode.SelectRead))
{
byte[] checkConn = new byte[1];
if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
{
throw new IOException();
}
}
if (stream.DataAvailable)
{
//Read the first command
WriteToConsole("Waiting for next command");
data = ReadStringFromClient(client, stream);
WriteToConsole("Received Command: " + data);
}
}
...代码继续...
ReadStringFromClient 代码:
private string ReadStringFromClient(TcpClient clientATF, NetworkStream currentStream)
{
int i;
string builtString;
byte[] stringFromClient = new byte[256];
if (clientATF.Connected && currentStream.CanRead)
{
i = currentStream.Read(stringFromClient, 0, stringFromClient.Length);
builtString = System.Text.Encoding.ASCII.GetString(stringFromClient, 0, i);
}
else
{
return "Connection Error";
}
return builtString;
}