Question

I made this TCP client and it is working but when it checks for incoming stream it pauses app...(Source code - https://app.box.com/s/7ly47ukztlo5eta3wqbk) Here is that part :

        void check()
        {
            if (tcpclnt.Connected == true)
            {
                NetworkStream stm2 = tcpclnt.GetStream();
                if (stm2.CanRead)
                {
                    // Reads NetworkStream into a byte buffer. 
                    byte[] bytes = new byte[tcpclnt.ReceiveBufferSize];

                    // Read can return anything from 0 to numBytesToRead.  
                    // This method blocks until at least one byte is read.
                    stm2.Read(bytes, 0, (int)tcpclnt.ReceiveBufferSize);

                    // Returns the data received from the host to the console. 
                    string returndata = Encoding.UTF8.GetString(bytes);

                    log("SERVER: " + Environment.NewLine + returndata + Environment.NewLine);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            check();
        }
Was it helpful?

Solution

Your method check() 'pauses' the app because its job is currently executed in the UI thread.

If you don't want that your method freezes the UI, you should schedule the execution of the method in a background thread, different from your UI thread.

You can do that using a BackgroundWorker thread. An example, as suggested by @qujck, is here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top