Is there any way of being notified when something subscribes to an event in my class, or do I need to wrap subscription/unsubsription in methods eg:
public class MyClass : ISomeInterface
{
public event SomeEventHandler SomeEvent; //How do I know when something subscribes?
private void OnSomeEventSubscription(SomeEventHandler handler)
{
//do some work
}
private void OnSomeEventUnsubscription(SomeEventHandler handler)
{
//do some work
}
}
instead of
public class MyClass : ISomeInterface
{
private SomeEventHandler _someEvent;
public void SubscribeToSomeEvent(SomeEventHandler handler)
{
_someEvent += handler;
//do some work
}
public void UnsubscribeFromSomeEvent(SomeEventHandler handler)
{
_someEvent -= handler;
//do some work
}
}
The reason I ask is because the event is already exposed directly on a ISomeInterface
but this particular implementation needs to know when stuff subscribes/unsubscribes.
A delegate is declared outside a class whereas, an event is declared inside a class. To invoke a method using a delegate object, the method has to be referred to the delegate object. On the other hand, to invoke a method using an event object the method has to be referred to the event object.
The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.
Event handlers In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button. To receive notifications when the event occurs, your event handler method must subscribe to the event.
To subscribe to events programmatically Use the addition assignment operator ( += ) to attach an event handler to the event.
You can write custom accessors for your event:
private SomeEventHandler _someEvent;
public event SomeEventHandler SomeEvent
{
add
{
_someEvent += value;
Console.WriteLine("Someone subscribed to SomeEvent");
}
remove
{
_someEvent -= value;
Console.WriteLine("Someone unsubscribed from SomeEvent");
}
}
Thomas has answered this already but thought I'd also add that you may need to lock any critical section in the add remove sections since event subscription is never thread safe, i.e. you have no idea who is going to connect to you or when. E.g.:
private readonly object _objectLock = new object();
private SomeEventHandler _someEvent;
public event SomeEventHandler SomeEvent
{
add
{
lock(_objectLock)
{
_someEvent += value;
// do critical processing here, e.g. increment count, etc could also use Interlocked class.
} // End if
} // End of class
remove
{
lock(_objectLock)
{
_someEvent -= value;
// do critical processing here, e.g. increment count, etc could also use Interlocked class.
} // End if
} // End if
} // End of event
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With