を使用して、私は非同期ネットワークストリームを返すために、デリゲートを使用して次のコード実行している:それは動作しますが、私のCPU使用率が屋根を突き破ってある高いCPU%デリゲート
static void Main(string[] args)
{
NetworkStream myNetworkStream;
Socket socket;
IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), xxxx);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect(maxPort);
myNetworkStream = new NetworkStream(socket);
byte[] buffer = new byte[1024];
int offset = 0;
int count = 1024;
string Command = "LOGIN,,,xxxx\n";
ASCIIEncoding encoder = new ASCIIEncoding();
myNetworkStream.BeginRead(buffer, offset, count, new AsyncCallback(OnBeginRead), myNetworkStream);
myNetworkStream.Write(encoder.GetBytes(Command), 0, encoder.GetByteCount(Command));
while (true) { }
}
public static void OnBeginRead(IAsyncResult ar)
{
NetworkStream ns = (NetworkStream)ar.AsyncState;
int bufferSize = 1024;
byte[] received = new byte[bufferSize];
ns.EndRead(ar);
int read;
while (true)
{
if (ns.DataAvailable)
{
string result = String.Empty;
read = ns.Read(received, 0, bufferSize);
result += Encoding.ASCII.GetString(received);
received = new byte[bufferSize];
result = result.Replace(" ", "");
result = result.Replace("\0", "");
result = result.Replace("\r\n", ",");
Console.WriteLine(result);
}
}
}
を(50% Intel Core i3上で)、明らかに私はそれを間違ってやっていますが、どうですか?あなたは、メインスレッド上で継続的にループしている
おかげ
'while(true)'は決して終了せず、CPUは無限にループし続けます。 –
あなたがしようとしていることを明記してください。明確ではありません。しかし、あなたのCPU使用率が高いのは、あなたがきちんとした無限ループを使っているということです( 'while(true)')。 –
私はIP電話から非同期フィードを返そうとしていますが、IPEndPointは電話サーバーに接続されているポートにリンクされています。 – JMK