Home > Back-end >  C# TCP add Client thread-safe List<T>
C# TCP add Client thread-safe List<T>

Time:01-07

In the below code I am adding new clients to the clientList:

public partial class Form1 : Form
    {
        TcpListener tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
        private int appStatus = 0;
        TcpClient client;
        TcpClient streamData;
        List<TcpClient> clientList = new List<TcpClient>();
        NetworkStream networkStream;
        Thread th_StartListen, th_inPutStream, th_outPutStream, th_checkConnection;
        StringBuilder strOutput;



        public Form1()
        {
            InitializeComponent();
            customizeDesign();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            th_StartListen = new Thread(new ThreadStart(StartListen));
            th_StartListen.Start();
            txtCmdOutput.Focus();
        }


        private void StartListen()
        {
            //Creating a TCP Connection and listening to the port
            tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
            tcpListener.Start();
            toolStripStatusLabel1.Text = "Listening on port 6666 ...";
            int counter = 0;
            appStatus = 0;

            
            while (true)
            {
                try
                {
                    client = tcpListener.AcceptTcpClient();
                    counter  ;
                    clientList.Add(client);

                    clientList.AsParallel().ForAll(item => clientList.Add(client));

                    
                    Parallel.ForEach(clientList, item =>
                    {
                        lock (clientList)
                            clientList.Add(client);
                    });



                    IPEndPoint ipend = (IPEndPoint)client.Client.RemoteEndPoint;
                    //Updating status of connection
                    toolStripStatusLabel1.Text = "Connected from "   IPAddress.Parse(ipend.Address.ToString());
                    appStatus = 1;
                    
                    th_outPutStream = new Thread(delegate () { outPutStream(client); });
                    th_outPutStream.Start();
                    th_inPutStream = new Thread(delegate () { inPutStream(client); });
                    th_inPutStream.Start();
                    th_checkConnection = new Thread(checkConnection);
                    th_checkConnection.Start();
                }
                catch (Exception err)
                {
                    {
                        Cleanup();
                    }
                }
            }
        }

I was advised that using a non-thread-safe List<T> to keep a list of clients is not a good solution.

So I was wondering how I could apply a thread-safe List<T> as to add the clients without encountering any errors.

So I attempted to do the following:

clientList.AsParallel().ForAll(item => clientList.Add(client));

Could anyone suggest a correct methodology?

Is the above code thread-safe? Is there a chance of the processed list getting could get corrupted? Or should I use a lock before adding?

Parallel.ForEach(clientList, item =>
                    {
                        lock (clientList)
                            clientList.Add(client);
                    });

CodePudding user response:

The questions were answered in the comments.

  • Related