Working with Event Handlers in .NET -
when adding handlers indiscriminately object's events, realized can attach same handler event many times like. means handler called once each time attached.
i'm wondering these things:
- is there way @ handlers have been added object's event?
- is possible remove handlers event?
- where these correlations between event , handler stored?
if event marked c# event keyword there's no way outside object see subscribers - requisite information not visible.
from inside, can done, though complex , relies on details of implementation might change (though, haven't yet).
a workaround might useful though, it's valid remove handler that's not there - no exception thrown.
so code valid:
myconnection.closing -= connectionclosinghandler; myconnection.closing += connectionclosinghandler;
if you're subscribed event, first line removes subscription.
if you're not subscribed event, first line nothing.
the second line hooks new subscription, , you're guaranteed not notified multiple times.
to answer last bullet point, when declare normal event:
public event propertychangedeventhandler changed;
the compiler creates member variable of type propertychangedeventhandler
stores subscribers. can take on storage if want:
public event propertychangedeventhandler changed { add { ... } remove { ... } }
the use of -=
, +=
modify subscription isn't syntactic sugar - delegates immutable, , new instance returned when add or remove handler. have @ delegate
, multicastdelegate
(both msdn links) more information on how works.
Comments
Post a Comment