Xap*_*Xap 3 c# sockets multithreading
我有一个C#类执行无限循环,直到条件变量设置为true.还有另一个等待网络消息的类,当接收到消息时,调用另一个类将条件变量修改为true,这样就可以退出while循环.等待消息是在一个单独的线程中完成的:
修饰符类:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
而另一类:
public class Otherclass{
bool docontinue = true;
public void postMessage(string input)
{
docontinue = true;
}
public void wait()
{
while(!docontinue)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是虽然发送了一条消息,程序仍然停留在while(!docontinue).我怀疑问题是变量docontinue没有被修改但我不知道问题是否在其他地方.
这里有各种各样的问题 -
对您的问题的第一个直接回答是,您需要使用volatile声明您的布尔字段:
private volatile bool doContinue = true;
Run Code Online (Sandbox Code Playgroud)
话虽这么说,有一个没有正文的while循环的循环是非常糟糕的 - 它将在该线程上消耗100%的CPU,并且只是无限期地"旋转".
对这种情况更好的方法是用WaitHandle替换你的while循环,比如ManualResetEvent.这允许您等待重置事件,并阻止,直到您准备好继续.您在另一个线程中调用Set()以允许执行继续.
例如,试试这个:
public class Otherclass{
ManualResetEvent mre = new ManualResetEvent(false);
public void PostMessage(string input)
{
// Other stuff here...
mre.Set(); // Allow the "wait" to continue
}
public void Wait()
{
mre.WaitOne(); // Blocks until the set above
}
}
Run Code Online (Sandbox Code Playgroud)