[英]C# TCP add Client thread-safe List<T>
In the below code I am adding new clients to the clientList
:在下面的代码中,我将新客户添加到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.我被告知使用non-thread-safe List<T>
来保留客户端列表并不是一个好的解决方案。
So I was wondering how I could apply a thread-safe List<T>
as to add the clients without encountering any errors.所以我想知道如何应用thread-safe List<T>
来添加客户端而不会遇到任何错误。
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);
});
The questions were answered in the comments.评论中回答了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.