加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

从C#中的另一个线程修改类属性

发布时间:2020-12-16 01:43:13 所属栏目:百科 来源:网络整理
导读:我有一个C#类执行无限循环,直到条件变量设置为true.还有另一个等待网络消息的类,当接收到消息时,调用另一个类将条件变量修改为true,这样就可以退出while循环.等待消息是在一个单独的线程中完成的: 修饰符类: public class Modifier{Otherclass log;private
我有一个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());
                }
            }
}

而另一类:

public class Otherclass{
    bool docontinue = true;
    public void postMessage(string input)
    {
         docontinue = true;
    }

    public void wait()
    {
          while(!docontinue)
          {
          }
    }
}

问题是虽然发送了一条消息,程序仍然停留在while(!docontinue).我怀疑问题是变量docontinue没有被修改但我不知道问题是否在其他地方.

解决方法

这里有各种各样的问题 –

对您的问题的第一个直接回答是,您需要使用volatile声明您的布尔字段:

private volatile bool doContinue = true;

话虽这么说,有一个没有正文的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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读