客户端线程抛出状态异常并停止C#

时间:2016-03-15 18:43:27

标签: c# multithreading networking server

我正在尝试创建两个连接到服务器的客户端线程。当有两个连接(threadsArray中的两个条目)时,我想要宣布开始。但是代码永远不会在threadRequest.annouceStart()调用。

通过调试,我确定在服务器以第二个客户端的形式侦听另一个连接时,正在停止创建的第一个线程。这是“冻结”,因为服务器挂起等待停止第一个线程的另一个连接?

static void Main(string[] args)
{
    runServer();
}

static void runServer()
{
    TcpListener listener;
    Socket connection;
    Handler threadRequest;
    string defaultName = "";
    int defaultScore = 0;
    int i = 0;
    Thread[] threadsArray = new Thread[2];

    try
    {
        listener = new TcpListener(IPAddress.Any, 43); 
        listener.Start();
        Console.WriteLine("Quiz Server launched");

        Console.WriteLine("A default user has been created for testing purposes");

        while(true) //main game loop
        {

                connection = listener.AcceptSocket();                      
               threadRequest = new Handler();

                threadsArray[i] = new Thread(() => threadRequest.clientInteraction(connection, teamInformation));
                threadsArray[i].Name = "Team" + (i + 1);

                threadsArray[i].Start();
                i++;


                if (threadsArray[1] != null)
                {
                    if (threadsArray[1].ThreadState == ThreadState.Running
                        && threadsArray[0].ThreadState == ThreadState.Running)
                    {
                        foreach (Thread thread in threadsArray)
                        {
                            threadRequest.announceStart(connection, teamInformation);
                        }
                    }
                }



        }

    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: " + e.ToString());
        Console.ReadKey();
    }
}

编辑:添加了Handler类定义。

class Handler {

        public static string interactionType;
        public static string pTeamName;
        public static string pAnswer;

public void announceStart(Socket connection, ConcurrentDictionary<string, int> teamInformation)...

public void clientInteraction(Socket connection, ConcurrentDictionary<string, int> teamInformation)...

public static void parseStrings(StreamReader sr, string recievedLine, out string pTeamName,
            out string pAnswer)...

static void findInteractionType(out string interactionType, string clientString)...

}

1 个答案:

答案 0 :(得分:0)

感谢Andrey Polyakov的评论。

“如果执行方法返回,则线程停止。对于clientInteraction()方法,你应该在这种方法中运行无限循环以避免线程终止。”