如何防止线程的两个副本复制方法和变量

时间:2018-08-14 18:04:54

标签: c# arrays string tcp stream

当前,我有两台客户端计算机将Kinect联合数据发送到服务器计算机,但是有两个单独的线程运行侦听器,因此(theString)变量的两个单独副本正在读取数据。有什么方法可以设置两个不同的变量,而不是创建重复的线程,而是从两个不同的客户端计算机读取数据。

public class AsynchIOServer
{
    static void Listeners(object state)
    {
        TcpListener listener = state as TcpListener;
        using (Socket socketForClient = listener.AcceptSocket())
        {
            if (socketForClient.Connected)
            {
                Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server.");
                using (NetworkStream networkStream = new NetworkStream(socketForClient))
                using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream))
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream))
                {
                    try
                    {
                        while (true)
                        {
                            string theString = streamReader.ReadLine();
                            if (string.IsNullOrEmpty(theString) == false)
                            {
                                Console.WriteLine("Message recieved by  " + theString);
                                var result = theString.Split(',');
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: " + ex.Message);
                    }
                }
            }
        }
        Console.WriteLine("Press any key to exit from server program");
        Console.ReadKey();
    }

    public static void Main()
    {

        TcpListener[] listeners =
        {
            new TcpListener(15), new TcpListener(10)
        };


        Console.WriteLine("***********This is Server program***********");
        Console.WriteLine("How many clients are going to connect to this server?:");
        int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());


        foreach (TcpListener listener in listeners)
        {
            listener.Start();
            for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
            {
                Thread newThread = new Thread(new ParameterizedThreadStart(Listeners));
                newThread.Start(listener);
            }
        }

    }
} 

1 个答案:

答案 0 :(得分:1)

使用状态对象,如下面的代码:

b