Store a list of EventHandlers to unsubscribe from
I have a class with a method, Register
that subscribes to a number of events on classes that it contains, using the standard aClass.SomeEvent += the_handler
. This class also has an Unregister
method that 开发者_运维问答unsubscribes from these events using -=
. This works just fine but we're finding that if we add a new event to subscribe to that it's very easy to forget to include the unsubscription in Unregister
. This manual method of maintaining event subscriptions is proving to be fragile.
Is there a way to maintain a list of subscriptions that can be iterated over and unsubscribed from dynamically? (And potentially iterate over and re-subscribe when calling Register
after Unregister
).
Some details: The class has a reference to 3 other classes (currently, but not definitively limited to 3), the various events on these classes are all of type EventHandler
or EventHandler<T>
.
how about getting invocation list from the EventHandler.GetInvocationList()
and then ierate through and manually remove/unregister them ? note, you only have access to the GetInvationList() method from the class that has that EventHandler, so you might need to expose a method UnregisterAll() to make sure it removes all the delagates in the event invocation list
you can also make sure your class inherits IDisposable
and with using(){ }
it will call Dispose which will clean up all subscribers
After a thorough look through SO I found this answer:
C# Dynamic Event Subscription
That does what I want (almost). I don't like having to name events using strings as and such I won't be pursuing this design any further. Even though it's not the design I want, the answer shows a very useful method to achieve the desired behaviour and as such I'm marking this as accepted.
精彩评论