Last active
August 29, 2015 14:02
-
-
Save wonderful-panda/a791f1e0a785bd018e17 to your computer and use it in GitHub Desktop.
Weak Eventの実装?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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