c# - 根据来自不同线程的条件写入线程中的 TCP 流
问题描述
我有两个线程,第一个从流中读取,第二个写入流。我在两个线程的上层还有一个名为“flag”的变量(默认为 false)。当满足某个条件时,“读取”线程将此标志修改为真。根据该标志,如果为真,则写入线程将某些内容写入流中。
一旦我写入流,我将标志更改为其原始值 - false,我在同一个写入线程中执行 if 语句。
现在有一个难题:如果标志为真,我进入 if 语句,并在 if 语句中将标志的值更改为 false。但是, if 中的“write”语句永远不会执行。看起来当 if 语句将标志评估为 true 或 false 时,它已经在 if 语句中更改为 false。为什么以及如何做到这一点。如果我在 if 语句中注释掉标志更改为 false 的行,那么一切正常。写入流后,我需要将标志值更改为 false。
public static bool flag = false;
Thread readThread = new Thread(...
// the flag is changed to true inside this thread
Thread writeThread = new Thread(() =>
{
using (var writer = new StreamWriter(stream, Encoding.Unicode))
{
while (true)
{
if (flag == true) // flag should be true here, but it seems it is changed to false
{
var text = "Text to be written";
writer.WriteLine(text );
writer.Flush();
flag = false; // flag is changed to false here, if I take out this line, the write statement is executed, otherwise, no
Thread.Sleep(1000);
}
}
}
}
解决方案
推荐阅读
- google-slides-api - Google Slides API batchUpdate 返回 500 内部错误
- python - Tensorflow 密集模型不断输出相同的输出
- java - 使用 WSDL2Java 时添加默认值(不修改模式)?
- c# - 根据特定单元格中的数据组合数据表中的行
- python - 显示隐藏小部件后如何将所有内容保持在正确位置?
- mongodb - 如何在下一个 js 应用程序的客户端显示猫鼬模式验证错误消息?
- java - 在 jgit 中使用 RevWalk 的 parseCommit 方法得到 NullPointerException
- node.js - 根据 _id 更新子数组中的所有元素
- python - 即使字符串模式匹配,re.match 也会返回 false
- angular - 如何在模板驱动的表单中以角度添加空格验证