我编写这段代码是为了将屏幕截图发送到多个连接的客户端。在客户端上工作正常,但在服务器端冻结了应用程序的 UI。我不明白是什么导致了这个问题。public void LoopClients(){ while (_isRunning) { TcpClient newClient = Server.AcceptTcpClient(); Thread t = new Thread(new ParameterizedThreadStart(HandleClient)); t.Start(newClient); }}public void HandleClient(object obj){ TcpClient client = (TcpClient)obj; BinaryFormatter binaryformatter = new BinaryFormatter(); while (client.Connected) { MainStream = client.GetStream(); binaryformatter.Serialize(MainStream, GrabDesktop()); }}private static Image GrabDesktop(){ System.Drawing.Rectangle bound = Screen.PrimaryScreen.Bounds; Bitmap screenshot = new Bitmap(bound.Width, bound.Height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(screenshot); graphics.CopyFromScreen(bound.X, bound.Y, 0, 0, bound.Size, CopyPixelOperation.SourceCopy); return screenshot;}任何改进代码或修复以解决问题的帮助或建议都会有很大帮助。
2 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
由于服务器正在列出新客户端以连接迭代循环,因此这可能会阻塞您的主 UI 线程。使用新线程运行它。
public void LoopClients()
{
Thread t1 = new Thread(() =>
{
while (_isRunning)
{
TcpClient newClient = Server.AcceptTcpClient();
Thread t = new Thread(new
ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}).Start()
}
注意:它并不总是需要new threads,HandleClient但它不是一个问题
- 2 回答
- 0 关注
- 197 浏览
添加回答
举报
0/150
提交
取消