using System;
using System.Collections.Generic;
using System.Text;
namespace TestWeakReference
{
class WeakEventHandler<T> : WeakReference where T : EventArgs
{
public WeakEventHandler() : base(null) { }
public WeakEventHandler(EventHandler<T> handler) : base(handler) { }
public WeakEventHandler(EventHandler<T> target, bool trackResurrection) : base(target, trackResurrection) { }
public new EventHandler<T> Target
{
get
{
return (EventHandler<T>)base.Target;
}
set
{
base.Target = value;
}
}
public static explicit operator EventHandler<T>(WeakEventHandler<T> weakEventHandler)
{
return weakEventHandler.Target;
}
}
class EventHost
{
private WeakEventHandler<EventArgs> _event = new WeakEventHandler<EventArgs>();
public event EventHandler<EventArgs> Event
{
add { _event.Target += value; }
remove { _event.Target -= value; }
}
public void FireEvent()
{
if (_event.Target != null)
{
_event.Target(this, EventArgs.Empty);
}
}
}
class EventClient
{
public void SayHello(object obj, EventArgs args)
{
Console.WriteLine("Hello~");
}
~EventClient()
{
Console.WriteLine("Client Dies!");
}
}
class Program
{
static void Main(string[] args)
{
EventHost host = new EventHost();
EventClient client = new EventClient();
host.Event += client.SayHello;
host.FireEvent(); // Client will say "Hello~";
client = null;
GC.Collect(); // Client dies here!
host.FireEvent(); // oops, nothing happen
}
}
}
using System.Collections.Generic;
using System.Text;
namespace TestWeakReference
{
class WeakEventHandler<T> : WeakReference where T : EventArgs
{
public WeakEventHandler() : base(null) { }
public WeakEventHandler(EventHandler<T> handler) : base(handler) { }
public WeakEventHandler(EventHandler<T> target, bool trackResurrection) : base(target, trackResurrection) { }
public new EventHandler<T> Target
{
get
{
return (EventHandler<T>)base.Target;
}
set
{
base.Target = value;
}
}
public static explicit operator EventHandler<T>(WeakEventHandler<T> weakEventHandler)
{
return weakEventHandler.Target;
}
}
class EventHost
{
private WeakEventHandler<EventArgs> _event = new WeakEventHandler<EventArgs>();
public event EventHandler<EventArgs> Event
{
add { _event.Target += value; }
remove { _event.Target -= value; }
}
public void FireEvent()
{
if (_event.Target != null)
{
_event.Target(this, EventArgs.Empty);
}
}
}
class EventClient
{
public void SayHello(object obj, EventArgs args)
{
Console.WriteLine("Hello~");
}
~EventClient()
{
Console.WriteLine("Client Dies!");
}
}
class Program
{
static void Main(string[] args)
{
EventHost host = new EventHost();
EventClient client = new EventClient();
host.Event += client.SayHello;
host.FireEvent(); // Client will say "Hello~";
client = null;
GC.Collect(); // Client dies here!
host.FireEvent(); // oops, nothing happen
}
}
}
More about this:
1. Using Weak References
2. Simulating “Weak Delegates” in the CLR
3. An Easy to Use Weak Referenced Event Handler Factory for .NET 2.0