I set an lambda expression as a event handler to a event
proxy.SomeEvent += (sender, e) => { doSomething(); };
But when debugging I found doSomething() was executed twice because somehow the above event assignment statement was executed twice.
So I want check whether the proxy.SomeEvent is null before calling the event assignment statement,like:
if(proxy.SomeEvent == null)
{
proxy.SomeEvent += (sender, e)=> { doSomething(); };
}
But I get a compiler error The event ‘Proxy.SomeEvent’ can only appear on the left hand side of += or -=
Since it is not possible to remove a lambda expression event handler by the -= operator, is there other way which enables me to check whether an event has already been assigned?
Your specific question was how to check to see if your lambda was already registered in order to avoid registering it twice. In the past I where I did not what to declare a separate method (which would support “-=”), I just assigned the lambda to a local variable before subscribing to the event.
The result is as expected, the lambda is only invoked once each time the event is raised, because the -= is effectively able to remove the subscription since you were able to provide the event handler to remove.
However, in more complex scenarios you may be using a lambda to perform a closure, and due to code paths you cannot easily maintain a reference to the original lambda that you used to subscribe to the event. If your case is this complex, I recommend creating a concrete closure class (similar to what the C# compiler does) and subscribe to the event using a method on an instance of your closure class. You will then need to override equals on your closure class to determine that the event subscription is the same based on the closure input values. This allows you to safely subscribe with one instance of your closure class and unsubscribe/resubscribe with a different instance at some later point.