为什么当我的 C# 应用程序开始侦听 tcp 套接字时,我的 CPU 使用率达到 99%
本文关键字:我的 CPU 使用率 套接字 tcp 应用程序 开始 为什么 | 更新日期: 2023-09-27 18:27:06
我创建了一个TCP套接字侦听应用程序。当我运行我的程序时,CPU 使用率上升到 99%
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding ascii = null;
while (!stopRecieving)
{
Thread.Sleep(500);
if (nStream.CanRead)
{
byte[] buffer = new byte[800000];
nStream.Read(buffer, 0, buffer.Length);
ascii = new ASCIIEncoding();
recvDt = ascii.GetString(buffer);
// --++ Normal msg
if (recvDt.Contains("--++"))
{
string d = "--++";
recvDt = recvDt.TrimStart(d.ToCharArray());
obj.SetSomeLab(recvDt, port );
}
}
Thread.Sleep(1000);
}
如果有人可以告诉我如何降低 CPU 使用率?问候
另一种方法是使用异步模式:
public void StartListening() {
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[0],11000);
Console.WriteLine("Local address and port : {0}",localEP.ToString());
Socket listener = new Socket( localEP.Address.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
try {
listener.Bind(localEP);
listener.Listen(10);
while (true) {
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(SocketListener.acceptCallback),
listener );
allDone.WaitOne();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine( "Closing the listener...");
}
public void acceptCallback(IAsyncResult ar) {
allDone.Set();
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Additional code to read data goes here.
}
在此处查看更多内容: http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx