fork download
  1. public abstract class LivetWeakEventListener : IDisposable
  2. {
  3. public abstract void Dispose();
  4. }
  5.  
  6. public class LivetWeakEventListener<TDelegate, TEventArgs> : LivetWeakEventListener where TEventArgs : EventArgs
  7. {
  8. private bool _disposed = false;
  9.  
  10. private EventHandler<TEventArgs> _handler;
  11. private TDelegate _resultHandler;
  12. private Action<TDelegate> _remove;
  13.  
  14. private static void ReceiveEvent(WeakReference listenerWeakReference, object sender, TEventArgs args)
  15. {
  16. var listener = listenerWeakReference.Target as LivetWeakEventListener<TDelegate, TEventArgs>;
  17.  
  18. if (listener != null)
  19. {
  20. var handler = listener._handler;
  21.  
  22. if (handler != null)
  23. {
  24. handler(sender, args);
  25. }
  26. }
  27. }
  28.  
  29. private static TDelegate GetStaticHandler(WeakReference listenerWeakReference, Func<EventHandler<TEventArgs>, TDelegate> conversion)
  30. {
  31. return conversion((sender, e) => ReceiveEvent(listenerWeakReference, sender, e));
  32. }
  33.  
  34. private LivetWeakEventListener() { }
  35.  
  36. public LivetWeakEventListener(Func<EventHandler<TEventArgs>, TDelegate> conversion, Action<TDelegate> add, Action<TDelegate> remove, EventHandler<TEventArgs> handler)
  37. {
  38. _handler = handler;
  39. _remove = remove;
  40.  
  41. _resultHandler = GetStaticHandler(new WeakReference(this), conversion);
  42.  
  43. add(_resultHandler);
  44. }
  45.  
  46. public override void Dispose()
  47. {
  48. GC.SuppressFinalize(this);
  49. this.Dispose(true);
  50. }
  51.  
  52. private void Dispose(bool disposing)
  53. {
  54. if (_disposed) return;
  55. _disposed = true;
  56. _remove(_resultHandler);
  57. }
  58.  
  59. ~LivetWeakEventListener()
  60. {
  61. Dispose(false);
  62. }
  63. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty