通过TCP发送图像时UI冻结

时间:2018-08-15 08:39:03

标签: c# bitmap tcpclient tcp-ip tcplistener

我编写此代码将屏幕快照发送给多个连接的客户端。在客户端可以正常工作,但冻结了服务器端应用程序的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 个答案:

答案 0 :(得分:1)

您是否意识到您正在while循环中创建新线程? 这意味着您将创建很多线程。 删除while循环,一切都会好起来。

答案 1 :(得分:0)

由于服务器列出了要通过迭代循环连接的新客户端,因此这可能会阻塞您的主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,但这不是一个探秘

相关问题