I'm currently developing an EventManager class to ensure that no events are left wired to dead WCF duplex clients, and also to control prevent multiple wiring from the same client to the one event.
Now basically, I'm what stuck with is trying to pass the event delegate to a function that will control the assignment like this.
var handler = new SomeEventHandler(MyHandler);
Wire(myObject.SomeEventDelegate, handler);
To call this:
private void Wire(Delegate eventDelegate, Delegate handler)
{
// Pre validate the subscription.
eventDelegate = Delegate.Combine(eventDelegate, handler);
// Post actions (storing subscribed event delegates in a list)
}
Update
The code for SomeEventDelegate wrapper is:
public Delegate SomeEventDelegate
{
get { return SomeEvent; }
set { SomeEvent = (SomeEventHandler) value; }
}
event SomeEventHandler SomeEvent;
Obviously the delegate is not being returned to the myObject.SomeEventDelegate And I cannot return the Delegate from the method because I need some validation after too. Do you have any idea on how to do this?
Use the C# ref
parameter modifier:
var handler = new SomeEventHandler(MyHandler);
Wire(ref myObject.SomeEventDelegate, handler);
private void Wire(ref Delegate eventDelegate, Delegate handler)
{
// Pre validate the subscription.
eventDelegate = Delegate.Combine(eventDelegate, handler);
// Post actions (storing subscribed event handlers in a list)
}
Note also that there exists some nice syntactic sugar (as of C# 2.0) for assigning and combining delegates (see this article, for example):
Wire(ref myObject.SomeEventDelegate, MyHandler);
private void Wire(ref Delegate eventDelegate, Delegate handler)
{
// Pre validate the subscription.
eventDelegate += handler;
// Post actions (storing subscribed event handlers in a list)
}
It has been pointed out to me that ref
only works with fields, not properties. In the case of a property, an intermediary variable can be used:
var tempDelegate = myObject.SomeEventDelegate;
Wire(ref tempDelegate, MyHandler);
myObject.SomeEventDelegate = tempDelegate;
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