首页 > 解决方案 > 根据来自不同线程的条件写入线程中的 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);
        }
      }
    }
  }

标签: c#multithreadingtcp

解决方案


推荐阅读