为什么我的事件处理程序仍被多次触发,即使我从事件中取消订阅?

时间:2018-03-13 03:57:52

标签: c# visual-studio events delegates event-handling

我有一个消费者类,它有一个从缓冲区getFromBuffer()获取的方法。缓冲区是另一个类。因此,每次将某些内容写入缓冲区时,我都会在使用者类中调用getFromBuffer方法;因此我使用事件处理程序。

class Buffer
{
      public delegate void GetFromBufferEvent();
      public static event GetFromBufferEvent getFromBuffer;
      string []buffer = new string[size]

      setBuffer()
      {
        //everytime something is written to the buffer
        getFromBuffer()
      }

}



class Consumer
{
      Buffer buffer = new Buffer();
      // Constructor
      Consumer(Buffer buffer)
      {
        Buffer.getFromBuffer -= new Buffer.GetFromBufferEvent(this.getFromBuffer);
        Buffer.getFromBuffer += new Buffer.GetFromBufferEvent(this.getFromBuffer);

        this.buffer = buffer;
      }

      ConsumerThread()
      {
        // continuously performs some events that trigger setBuffer in Buffer class
       // which in turn triggers getFromBuffer method in consumer class

      }

      getFromBuffer()
      {
       Console.WriteLine(Thread.CurrentThread.Name + "consumed" + string)
      }
}


Main
{
      Buffer buffer = new Buffer();

      // Pass the same buffer because they need to write to the same buffer
      Consumer c1 = new Consumer(buffer);
      Consumer c2 = new Consumer(buffer);

      Thread t1 = new(ThreadStart(c1.ConsumerThread));
      Thread t2 = new(ThreadStart(c2.ConsumerThread));

      t1.Name = ("C1");
      t2.Name = ("C2");

      t1.Start();
      t2.Start();


}

所以基本上有时像每次调用它会连续两次打印Thread.CurrentThread.Name +“consume”+ string。我认为问题是两个线程无法知道对方是否订阅了。因为它们是2个独立的线程,所以我不能设置一些标志,因为它们之间不会共享该标志。我怎样才能解决我的问题? (所有其他功能100%正常,问题源于事件订阅和取消订阅)请帮忙!

哦,我已尝试在getFromBuffer()

中取消订阅

0 个答案:

没有答案