b2sing4u

During runtime, some methods are subscribed/unsubscribed to an event.

myObject.Event += method1

myObject.Event += method2

myObject.Event -= method3

...

During runtime, at some point, I'd like to unsubscribe all methods from an event.

But, at that point, I don't know which methods are subscribed to that event.

So, using -= operator is not liable.

How can I do this

Is there any static method (in .NET library) like below

Event.Initialize(myObject.Event)



Re: .NET Base Class Library How to initialize event during runtime (not knowing which methods are subscribed)?

Mark Dawson

Hi,

you can explicitly declare your own delegate inside your class that you can then set to null which removes all of the event handlers. See my reply in this post for an example: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=1111240&SiteID=1

Mark.






Re: .NET Base Class Library How to initialize event during runtime (not knowing which methods are subscribed)?

b2sing4u

OK, I see.

But, I think your solution is not applicable to pre-defined events, like FileSystemWatcher.Changed event below

private FileSystemWatcher myWatcher = new FileSystemWatcher();

myWatcher.Changed += new FileSystemEventHandler(OnChanged1);

myWatcher.Changed += new FileSystemEventHandler(OnChanged2);

myWatcher.Changed -= new FileSystemEventHandler(OnChanged3);

myWatcher.Changed -= new FileSystemEventHandler(OnChanged4);

......





Re: .NET Base Class Library How to initialize event during runtime (not knowing which methods are subscribed)?

Peter Ritchie

Events are generally multicast delegates; but the interface to subscribe and unsubscribe can be custom. For events on a class you have no control over you'll have to manually unsubscribe each handler (i.e. with the -= operator).




Re: .NET Base Class Library How to initialize event during runtime (not knowing which methods are subscribed)?

nobugz

This thread shows a hack using Reflection. That code is specific to the Visible event and won't work for other events. I wouldn't recommend using something like this, there are sure to be better ways if you could explain why you're trying to do this and for what event.