使服务器同时进行两个线程

时间:2016-03-31 16:34:55

标签: c# multithreading server

我有两个线程在稍微不同的时间到达服务器程序中的某个点,都发送一个字符串。我希望服务器在此时暂停,直到两个线程都收到一个字符串然后继续。目前我正在使用Console.ReadKey();以暂停"暂停"线程。但这不是一个解决方案,因为我需要按两次键(每个线程一个)才能继续。

是否有可能在程序类中有一个全局计数器,所有线程都可以随时访问和编辑?与ConcurrentDictionary类似的概念。这样我可以根据哪个线程首先发送一个字符串来区分线程,并使程序挂起,直到计数器满足两个客户端已经回答为止。

class Program
{
    public static bool isFirstThread = false;

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

    static void runServer()
    {
        //server setup
        Thread[] threadsArray = new Thread[2];
        int i = 0;
        try
        {
            while(true) //game loop
            {
                Socket connection;
                connection = listener.AcceptSocket();
                threadRequest = new Handler();

                if(i==0) //first thread
                {
                    threadsArray[i] = new Thread(() => threadRequest.clientInteraction(connection, true);
                }
                else //not first thread
                {
                    threadsArray[i] = new Thread(() => threadRequest.clientInteraction(connection, false);
                }

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

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


class Handler 
{
    public void clientInteraction(Socket connection, bool isFirstThread)

    {
        string pAnswer = string.Empty;
        //setup streamReaders and streamWriters

        while(true) //infinite game loop
        {
            //read in a question and send to both threads.
            pAnswer = sr.ReadLine();
            Console.WriteLine(pAnswer);

            Console.ReadKey(); //This is where I need the program to hang

            awardPoints(); 

        }
    }
}   

这是我的代码正在做什么的粗略概念,为了避免问题膨胀,我已经砍掉了很多,所以可能会有一些我错过的错误。

理论上我可以从服务器发送问题字符串时设置一个计时器,但我宁愿不在这个阶段。

任何想法或指示都会非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用专为此目的而设计的System.Threading.Barrier:使一组线程中的每个线程等到所有线程都达到计算中的某个点。像runServer()这样初始化它:

Barrier barrier = new Barrier(2);

并在每个帖子的末尾执行此操作:

barrier.SignalAndWait();
相关问题