Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.

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


I call the loopClient() function in timer and than timer in button to run the program.
Any suggestion to improve the code or fix t resolve the problem would be great help.

What I have tried:

I have searched many solution but noting is quit helping in any ways.
Posted
Updated 15-Aug-18 0:39am
v2
Comments
F-ES Sitecore 15-Aug-18 6:13am    
If it's freezing the UI then run the code in its own thread using BackgroundWorker or the Thread class or some other way to do this. Google "winforms run code on new thread" and I'm sure you'll find lots of examples.
Member 13714031 15-Aug-18 6:32am    
I create a new thread to run in the loopclient() function. Now application works fine.Thanks for help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900