If you subscribe the .net event with the same subscribe more then once, then your subscribed method will be called the same times as subscribed. And if you unsubscribe just once, then it will be just one minus to the call. Meaning you have to unsubscribe same no of times as subscribed, otherwise u will be keep informed. Somtimes you don't want to do it.
In order to to prevent an event Handler to be hooked twice, we can implement event as following.
private EventHandler foo;
public event EventHandler Foo
{
add
{
if( foo == null || !foo.GetInvocationList().Contains(value) )
{
foo += value;
}
}
remove
{
foo -= value;
}
}
Now I would like to implement Postsharp EventInterceptionAspect to make this solution generic, so that I can apply PreventEventHookedTwiceAttribute
on every event to save lot of code. But I can't figure out how to check the second part of the following condition in add. I mean foo.GetInvocationList().Contains(value). My PreventEventHookedTwiceAttribute looks like following.
[Serializable]
public class PreventEventHookedTwiceAttribute: EventInterceptionAspect
{
public override void OnAddHandler(EventInterceptionArgs args)
{
if(args.Event == null || secondConditionRequired) // secondConditionRequired means it is required.
{
args.ProceedAddHandler();
}
}
}
I don't need to override OnRemoveHandler, as default functionality is enough here.