The following methods are part of a base class which enables derived classes to specify who should be notified by an event.
protected void RaiseEvent<TEventArgs>(EventHandler<TEventArgs> updateEvent, TEventArgs eventArgs, UpdateReceivers updateReceivers)
where TEventArgs : EventArgs
{
EventHandler<TEventArgs> handler = updateEvent;
if (handler != null)
{
if (updateReceivers.ToAllSubscribers)
{
handler(this, eventArgs);
}
else
{
NotifySpecifiedReceiver(handler, eventArgs, updateReceivers.Receiver);
}
}
}
private void NotifySpecifiedReceiver<TEventArgs>(EventHandler<TEventArgs> handler, TEventArgs eventArgs, object updateReceiver)
where TEventArgs : EventArgs
{
foreach (Delegate @delegate in handler.GetInvocationList())
{
// is the delegates target our receiver?
// but this doesnt work for anonymous methods :(
if (@delegate.Target == updateReceiver)
{
try
{
@delegate.DynamicInvoke(this, eventArgs);
}
catch (Exception ex)
{
}
}
}
}
To notify only a specific receiver, the method is used like this: (the receiver has to be subscribed of course)
event EventHandler<SomethingChangedEventArgs> SomethingChanged;
RaiseEvent(SomethingChanged, args, UpdateReceivers.Single(receiver));
This will only raise the delegates "pointing" to the receiver.
My problem here is when i use a anonymous method to subscribe to the SomethingChanged event its doesnt work when i use this event to notify the object which subscribed to it.
class EventConsumer
{
private EventSource _eventSource;
private void SubscribeEvents()
{
// ReactOnEvent() will not be called because the check [@delegate.Target == updateReceiver] doesnt work for anonymous methods
_eventSource.MyStateChanged += (sender, e) => ReactOnEvent();
_eventSource.PublishCurrentState(this);
}
}
class EventSource
{
// multiple objects are subscribed to this event
event EventHandler<MyStateChangedEventArgs> MyStateChanged;
public void GetCurrentState(object receiver)
{
// receiver ask for the current state, only raise event for him
RaiseEvent(MyStateChanged, args, UpdateReceivers.Single(receiver));
}
}
Is it possible the get the instance containing a anonymous method? or should i use a complete different approach to solve my problem?