Search code examples
c#bitmaptcpclienttcptcplistener

UI freezes when sending image over tcp


I write this code to send screenshot to multiple connected clients.Works fine on clients end but freezes the UI of application on server side.I don't understand what cause that problem.

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;
}

Any help or suggestion to improve the code or fix to solve the problem would be great help.


Solution

  • Since the server is listing for new clients to connect with an iterative loop, this might block your main UI thread. Run that using a new thread.

    public void LoopClients()
    {       
        Thread t1 = new Thread(() =>
        {   
            while (_isRunning)
            {
                TcpClient newClient = Server.AcceptTcpClient();
    
                Thread t = new Thread(new 
                 ParameterizedThreadStart(HandleClient));
                t.Start(newClient);
            }
        }).Start()      
    }
    

    Note: Its not always required to have new threads for HandleClient however its not a probelm