【发布时间】:2016-07-22 10:56:57
【问题描述】:
我有一个使用两个客户端线程和一个服务器的程序。在我的程序中,我希望一个线程中的值影响另一个线程的路径。
更具体地说,我在服务器中有这段代码:
class Handler
{
public void clientInteraction(Socket connection, bool isFirstThread, Barrier barrier)
{
string pAnswer = string.Empty;
string endGameTrigger = 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);
awardPoints();
writeToConsole("Press ENTER to ask another question or enter 0 to end the game", isFirstThread);
if(isFirstThread == true)
{
endGameTrigger = Console.ReadLine(); //this is only assigning to one thread...
}
barrier.SignalAndWait();
if(endGameTrigger == "0")//...meaning this is never satisfied in one thread
{
endGame();
}
}
}
}
布尔值isFirstThread 是在线程的构造函数中设置的值,我可以检测到哪个线程首先连接到该值。
是否有某种方式,或者可能是线程方法,允许第二个连接的线程检测到第一个线程中的endGameTrigger 已设置,因此两个线程都正确执行endGame() 方法。
【问题讨论】:
-
使其成为字段而不是本地字段。您还需要添加同步。
标签: c# multithreading server