我有一个C#类,执行无限循环直到条件变量被设置为true。另一个类等待网络消息,当接收到消息时,调用另一个类修改条件变量为true,以便退出while循环。等待消息是在单独的线程中完成的:
修改器类:
问题在于程序在 while(!docontinue) 循环中卡住了,尽管已发送消息。我怀疑问题在于变量 docontinue 没有被修改,但我不知道问题是否出在其他地方。
修改器类:
public class Modifier{
Otherclass log;
private static NetworkStream theStream;
private StreamReader theInput;
public Modifier(Otherclass other, NetworkStream str)
{
this.log = other;
theStream = str;
theInput = new StreamReader(theStream);
Thread listenThread = new Thread(new ThreadStart(listen));
listenThread.Start();
}
public void listen()
{
while (true)
{
log.postMessage(theInput.ReadLine());
}
}
}
另一个类:
public class Otherclass{
bool docontinue = true;
public void postMessage(string input)
{
docontinue = true;
}
public void wait()
{
while(!docontinue)
{
}
}
}
问题在于程序在 while(!docontinue) 循环中卡住了,尽管已发送消息。我怀疑问题在于变量 docontinue 没有被修改,但我不知道问题是否出在其他地方。