你好我在运行这个线程时有很高的CPU使用率(15-16%),它是一个应该保持循环的线程,除非" ssStop"设置为true(有效),但是,当它运行时,我打开任务管理器,我看到该程序正在耗尽15%的计算机处理能力,一旦线程被占用,它就会下降到1-2%退出。即使使用我发现在线搜索此问题的EventWaitHandle,它仍然很高,有人知道我在这里做错了吗?:
public void Receive()
{
try
{
bool firstTimeRun = true;
TcpListener ssTcpListener = new TcpListener(IPAddress.Any, 1500);
TcpClient tcpReceiver;
ssTcpListener.Start();
while (!ssStop)
{
//Start listening for connection.
//Accept any incoming connection requests on port 1500.
tcpReceiver = new TcpClient();
if (ssTcpListener.Pending())
{
tcpReceiver = ssTcpListener.AcceptTcpClient();
}
if (tcpReceiver.Connected)
{
//looped for first time; receives whole image.
if (firstTimeRun)
{
//TCP connected. Receive images from contact
NetworkStream receivedNs = new NetworkStream(tcpReceiver.Client);
Bitmap image = new Bitmap(receivedNs);
receivedImage = image;
pboScrnShare.Image = image;
receivedNs.Flush();
firstTimeRun = false;
}
//second time or higher looped; receives difference and overlays it.
else if (!firstTimeRun)
{
NetworkStream receivedNs = new NetworkStream(tcpReceiver.Client);
//Put image into picturebox.
receivedImage2 = new Bitmap(receivedNs);
receivedImage2.MakeTransparent(Color.Black);
Bitmap overlayedImage = new Bitmap(receivedImage.Width, receivedImage.Height);
using (Graphics gr = Graphics.FromImage(overlayedImage))
{
gr.DrawImage(receivedImage, new Point(0, 0));
gr.DrawImage(receivedImage2, new Point(0, 0));
}
try
{
pboScrnShare.Image = overlayedImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "pbo second run");
}
receivedImage2.Dispose();
if (this.InvokeRequired) { this.Invoke(new MethodInvoker(delegate() { receivedImage = overlayedImage; })); } else { receivedImage = overlayedImage; }
receivedNs.Flush();
}
tcpReceiver.Close();
}
myEventWaitHandle.WaitOne(10, true);
}
ssTcpListener.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Invited ReceiveSS()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:1)
您正在为连接刻录cpu周期忙轮询。考虑到大部分时间Pending
返回false,你的循环就像这样旋转:
while (!ssStop)
{
tcpReceiver = new TcpClient();
myEventHandle.WaitOne(10, false);
}
现在如果myEventHandle未设置,那么WaitOne
中的10ms延迟将有效地限制执行但我的猜测是设置事件以便WaitOne
立即返回true
。
没有必要轮询连接,因为AcceptTcpClient
将阻止等待连接。因此,如果您稍微更改了代码,它应该按预期工作:
while (!ssStop)
{
TcpClient tcpReceiver = ssTcpListener.AcceptTcpClient(); // this blocks
...
}