Hi Michael, This is an awesome pattern for solving this problem. I use it myself quite a lot. I think it is perfect for Stephen.
Cheers. James. From: [email protected] [mailto:[email protected]] On Behalf Of Michael Minutillo Sent: Monday, 2 April 2012 11:11 To: ozDotNet Subject: Re: Unhooking events from Handler In the past I have done something like this: class Disposable : IDisposable { private readonly Action _action; public Disposable(Action action) { _action = action; } public void Dispose() { _action(); } } public interface IHandle<TMessage> { void Handle(TMessage message); } public static class Events { private static readonly IList<object> _handlers = new List<object>(); public static IDisposable Register(object o) { _handlers.Add(o); return new Disposable(() => _handlers.Remove(o)); } public static void Raise<TMessage>(TMessage message) { foreach(var handler in _handlers.OfType<IHandle<TMessage>>()) handler.Handle(message); } } That way the registration code returns some kind of "subscription token". Whoever adds the handler is responsible for disposing of the token and therefore cancelling the subscription. There's lots you can do around background threads, error handling, locking (for thread safety) etc. but the above is the basic skeleton I end up using. Michael M. Minutillo Indiscriminate Information Sponge http://codermike.com On Mon, Apr 2, 2012 at 9:27 AM, David Walker <[email protected]<mailto:[email protected]>> wrote: http://msdn.microsoft.com/en-us/library/ee658248.aspx search on the page for 'static event' should find the best ways to do this. Typically the child will unsubscribe itself inside Dispose() On 2 Apr 2012, at 02:21, Stephen Price wrote: > Hey all, > > I've got a Static class that's behaving like an EventHandler in that you > assign values to it via an operator + or - method. > > I need a method on this thing or some way that I can unhook the ones from one > particular class (called from the dispose of that class) so that it can > remove only the ones that were added from that class. Its accepting an Enum, > so is there a way to see the owner of an Enum or where it was created? > > Or do I need to store something along with the Enum that can later be used to > identify who attached it? > > If you imagine it as a Static eventhandler, how can I look through the > references and only unhook the ones from a particular class. (assuming > internally you can loop through each handler. > The actual problem is that it's causing a memory leak if I don't unhook these > things when that page/veiwmodel is disposed. > > hope the above makes some kind of sense to someone. :) > > cheers, > Stephen
