为什么这个通用的C#WeakEvent监听器不起作用?

时间:2012-05-03 15:55:27

标签: c# generics design-patterns weak-references

我试图通过开发一个通用的弱事件监听器来节省时间,我可以通过一个Action来传递。事情似乎工作正常,直到一个未注册。这似乎取消了所有注册。我感到困惑的是为什么,以及为什么这与IweakEventListener参数的 this 相同?

  public class GenericWeakEventListener : IWeakEventListener
  {
    #region EventAction

    /// <summary>
    /// Action to take for the event
    /// </summary>
    private Action<Type, object, EventArgs> _eventAction;

    /// <summary>
    /// Gets or sets the action to take for the event
    /// </summary>
    //[DataMember]
    public Action<Type, object, EventArgs> EventAction
    {
      get
      {
        return _eventAction;
      }

      private set
      {
        if (EventAction != value)
        {
          _eventAction = value;
        }
      }
    }

    #endregion EventAction

    #region Constructors

    public GenericWeakEventListener(Action<Type, object, EventArgs> action)
    {
      EventAction = action;
    }

    #endregion Constructors

    #region Public Methods

    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
      if (EventAction != null)
      {
        EventAction(managerType, sender, e);
      }

      return true;
    }

    #endregion Public Methods
  }

修改

这是听众代码:

  public class SomeClient
  {
    public int ID { get; set; }

    private Timer timer = null;
    private Timer timer2 = null;

    public SomeClient(int id, SomeService service)
    {
      ID = id;
      //EventHandler<GenericEventArgs<string>> d = (o, s) => Console.WriteLine("Client {0}: {1}", ID, s.Item);
      if (service != null) SomeEventChangedEventManager.AddListener(service, new GenericWeakEventListener((t, s, e) => { Console.WriteLine("SomeEvent: " + ID); }));

      timer = new Timer { AutoReset = true, Interval = 1000 };
      SomeTimerElapsedEventManager.AddListener(timer, new GenericWeakEventListener((t, s, e) => { Console.WriteLine("SomeTimer: " + ID); }));
      timer.Start();
    }
  }

这是发布商的代码:

  public class SomeService
  {
    public event EventHandler<GenericEventArgs<string>> SomeEvent;

    public SomeService()
    {
      System.Timers.Timer timer = new Timer { AutoReset = true, Interval = 1000 };
      timer.Elapsed += (sender, args) => { if (SomeEvent != null) SomeEvent(this, new GenericEventArgs<string>(Guid.NewGuid().ToString())); };
      timer.Start();
    }
  }

这是主方法的代码:

public static void Main(string[] args)
{
  SomeService service = new SomeService();
  List<SomeClient> clients = new List<SomeClient>();

  // Build clients
  for (int x = 0; x < 5; x++)
  {
    clients.Add(new SomeClient(x + 1, service));
  }

  System.Timers.Timer timer = new Timer { AutoReset = true, Interval = 5000 };
  timer.Elapsed += (s, a) =>
    {
      if (clients.Count == 0)
      {
        return;
      }

      Console.WriteLine("Removing\r\n");
      clients.RemoveAt(0);
      GC.Collect();
    };
  timer.Start();

  Console.ReadLine();
}

这是输出: SomeEvent:1 SomeEvent:2 SomeEvent:3 SomeEvent:4 SomeEvent:5 SomeTimer:2 SomeTimer:3 SomeTimer:4 SomeTimer:1 SomeTimer:5 SomeEvent:1 SomeEvent:2 SomeEvent:3 SomeEvent:4 SomeEvent:5 SomeTimer:1 SomeTimer:2 SomeTimer:3 SomeTimer:4 SomeTimer:5 SomeEvent:1 SomeEvent:2 SomeEvent:3 SomeEvent:4 SomeEvent:5 SomeTimer:2 SomeTimer:3 SomeTimer:4 SomeTimer:5 SomeTimer:1 SomeEvent:1 SomeEvent:2 SomeEvent:3 SomeEvent:4 SomeEvent:5 SomeTimer:1 SomeTimer:2 SomeTimer:3 SomeTimer:5 SomeTimer:4 SomeEvent:1 SomeEvent:2 SomeEvent:3 SomeEvent:4 SomeEvent:5 除去

如果没有通用弱事件侦听器,则输出继续,不带1,然后不带2,依此类推。

1 个答案:

答案 0 :(得分:3)

编辑来自OP编辑:知道了。以下是我的想法:

您正在声明SomeClient拥有的lambda,并且包含对实例变量ID的外部闭包。这使得lambda通过SomeEventChangedEventManager作为委托传递给SomeService上的事件,这取决于ID实例的继续存在。

删除SomeClient实例时,该lambda所需的ID变量超出范围并且是GCed。但是,我没有看到此代码的任何部分从SomeService的SomeEvent的处理程序中删除此lambda。因此,lambda作为对匿名委托的引用保留在内存中,但它依赖的其他数据现在已经消失。这会导致运行时抛出异常,这会以某种方式被吞噬,并且不会导致整个程序爆炸。

但是,事件基本上按照它们附加的顺序执行处理程序委托(这是一个它们通常告诉你忽略的实现细节)已经停止执行,因为其中一个处理程序已经抛出。这使得删除第一个客户端似乎删除了所有客户端,而实际上这些客户端的处理程序没有执行,因为第一个处理程序出错了。

修复是双重的:

  • 定义lambda并将其存储为SomeClient的实例变量。这允许您保留对它的引用,这很重要,因为在确定相等性时不会在语义上比较委托,因此以下代码不起作用:

    SomeEvent += (a,b,c) => Foo(a,b,c);
    //the following line will not remove the handler added in the previous line,
    //because the two lambdas are compiled into differently-named methods
    //and so this is a different reference to a different method.
    SomeEvent -= (a,b,c) => Foo(a,b,c);
    
  • 在SomeClient上实现IDisposable和/或终结器。从列表中删除客户端时,GC调用的disposer / finalizer应该从SomeEvent侦听器中删除此实例的lambda(可能通过Manager上的RemoveListener()方法)。因为您保留了对指向确切添加内容的委托的引用,所以处理程序将被删除,因此不会执行,也不会出错。