Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save wonderful-panda/a791f1e0a785bd018e17 to your computer and use it in GitHub Desktop.

Select an option

Save wonderful-panda/a791f1e0a785bd018e17 to your computer and use it in GitHub Desktop.
Weak Eventの実装?
namespace WonderfulPanda.Gist
{
public class EventSourceSample
{
WeakEvent<EventArgs> _test = new WeakEvent<EventArgs>();
public event Test
{
add { _test.AddHandler(value); }
remove { _test.RemoveHandler(value); }
}
protected virtual OnTest(EventArgs e)
{
_test.RaiseEvent(e);
}
}
}
namespace WonderfulPanda.Gist
{
public class WeakEvent<TEventArgs> where TEventArgs: EventArgs
{
List<WeakReference> _handlers = new List<WeakReference>();
public void AddHandler(EventHandler<TEventArgs> handler)
{
lock (_handlers)
{
_handlers.Add(new WeakReference(handler));
}
}
public void RemoveHandler(EventHandler<TEventArgs> handler)
{
lock (_handlers)
{
_handlers.RemoveAll(w => !w.IsAlive || ((EventHandler<TEventArgs>)w.Target) == handler);
}
}
public void RaiseEvent(object sender, TEventArgs e)
{
EventHandler<TEventArgs> []handlers;
lock (_handlers)
{
handlers = _handlers.Where(w => w.IsAlive)
.Select(w => w.Target as EventHandler<TEventArgs>)
.Where(h => h != null)
.ToArray();
_handlers.RemoveAll(w => !w.IsAlive);
}
foreach (var h in handlers)
h(sender, e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment