Following on from this post - what are the disadvantages when using the -= then += approach suggested when I only ever want one handler event to fire?
_value.PropertyChanged -= _handlerMethod;
_value.PropertyChanged += _handlerMethod;
This doesn't guarantee that there is only one handler fired.
Another location could, potentially, subscribe your handler to your event multiple times. In this case, you will only remove the first handler call.
By inspecting the invocation list of the event, you could guarantee this behavior, if you truly only want a single handler to be subscribed at a time.
If you really want only one handler to execute, then you may want to use a settable property of the appropriate delegate type instead of an event. Only one delegate will be stored; you can execute the delegate the same as you would the event handler.
The idea here is that the -= operator is not going to do anything if your event handler is not assigned.
I don't personally like this approach, I think you should really aim to refactor your code so that you know that the event handler is assigned only once.
The disadvantages would be:
- possibility of race condition, if your app is multithreaded and the event gets fired when the handler is not assigned
- I am also not sure what happens when you run _value.PropertyChanged -= _handlerMethod when two copies of the handler are already assigned.
- messy code - obviously its not clear from the code which class and when is listening to the event
Related
I'm not new to C#, but events is one of the most confusing topics I confront in the language.
one of the questions is: where should I assign the event handler to the event, or the question in other form: why most events are raised in the subscriber constructor? what does it mean?
like this example (taken from the book Mastering Visual C# )
public ReactorMonitor(Reactor myReactor)
{
myReactor.OnMeltdown +=
new Reactor.MeltdownHandler(DisplayMessage);
}
Raise = generate. Events are not raised in the subscriber constructor. The subscriber does not raise events at all. The event source raises/generates events, and subscribers subscribe to, receive, and handle them.
Events in c# are nothing more than function pointers, i.e. a variable that contains a pointer (or list of pointers) to a function that matches a specific signature (typically Action<object,EventArgs>). Or in the words of this MSDN article:
Delegates are like C++ function pointers but are type safe.
When you subscribe to an event, you are essentially saying "Store the address of my function. When X happens, please call it (along with any other function whose address is stored)."
Thus the code
myReactor.OnMeltdown += Meldownhandler;
can be read as
objectThatRaisesEvents.FunctionPointer = MyHandler;
Notice that MyHandler is not followed by parentheses. If it were MyHandler() that means you are invoking the function, the value of the expression MyHandler() is actually the return value of the function; MyHandler by itself doesn't invoke the function or return its value but instead returns the address of the handler itself. So the above line of code takes the address of MyHandler and stores it in a variable named FunctionPointer.
When the object that raises events invokes FunctionPointer() it is telling c# to obtain the address of the function stored in FunctionPointer and invoke it.
So it is really calling MyHandler() indirectly. Thus these two lines do exactly the same thing:
objectThatRaisesEvents.FunctionPointer();
MyHandler();
Also notice the += in your example. In c# that is the equivalent of
objectThatRaisesEvents.FunctionPointer =
objectThatRaisesEvents.FunctionPointer + MyHandler;
We typically use that syntax because there might be several handlers that subscribe to an event. += has the effect of appending our handler to the list. You could use = instead, but it would unsubscribe any existing handlers.
To answer your question-- when should you subscribe to events? That is a very broad question, but typically
In an ASP.NET web page, you'd subscribe during the Init event.
In a Windows Form, you'd subscribe in the InitializeComponent method.
There are many other contexts of course... the bottom line is you should subscribe before you need to receive notifications of occurrences of the event.
The event is one of the standard features of .NET Framework built using delegate model implementing the Observer design pattern.
https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx
https://en.m.wikipedia.org/wiki/Observer_pattern
Where you subscribe to the event depends on the business rules, but most of the time you want to subscribe at the earliest possible moment which is usually the constructor of the class interested in the handling of the event.
When events should be raised on the other hand depends on what you are trying to communicate to the subscribers if it is a notification of the state change then you raise an event as soon as state is changed.
An event is a message sent by an object to signal the occurrence of an
action. The action could be caused by user interaction, such as a
button click, or it could be raised by some other program logic, such
as changing a property’s value.
So if I do something like this on my event declaration:
public event MyDelegate MyEvent = delegate { };
I read that this makes null checks redundant, that there will be a no-op subscriber.
I'm curious how this works under the hood. What exactly happens and is this a good practice, or should I stick with usual null check before firing the event handler?
The null checks aren't tricky because of an extra if - they are tricky because they're unreliable in a multi-threaded environment.
It's a trade-off. If you expect that the event will only have 0-1 delegates, using a (safe) null-check is probably better. If you expect to have multiple subscribers that keep subscribing and unsubscribing, you're better off with the "null-delegate". It does mean an extra delegate in the call chain, but that's usually cheap enough for most uses of events in .NET.
You wouldn't want to use it on e.g. a control that has 50 different events most of which never have a subscriber, or your behaviour changes based on whether there is a subscriber or not.
As for what happens under the hood, well... nothing. This does no magic whatsoever. The trick is in how += works on events / delegates.
If you have a null event, and use +=, it simply assigns a new delegate to the event. If there already is a delegate, it will create a new delegate, which is a combination of the previous delegate and the new one. If you use that null-delegate, it simply means that there is always some delegate to combine. The usual code for invoking an event can look something like this:
var ev = Click;
if (ev != null) ev();
This means that if there is no subscriber to the event, there is no invocation. In the null-delegate case, the code is further simplified to
Click();
This always means a delegate invocation - at the very least, your null-delegate is invoked. Sure, it doesn't actually do anything, but you keep the delegate invocation overhead. Again, this is rarely a problem, but there are cases where this is unacceptable.
Is there a problem if I subscribe to the same event three times with the eventHandler?
e.g.
a.SomethingChanged += new EventHandler(ChangeHandler);
a.SomethingChanged += new EventHandler(ChangeHandler);
a.SomethingChanged += new EventHandler(ChangeHandler);
Does this cause ChangeHandler to be invoked 3 times instead of 1? What is best way to handle this?
Note that these redundancies are not together but different areas of code paths.
Similary, is there an issue with unsubscribing from an event that is not registered?
e.g.
a.SomethingChanged -= new EventHandler(ChangeHandler); //ChangeHandler was never registered
If you subscribe to an an event more than once then your handler will be called the corresponding number of times - in your example three.
Whether this is a problem or not depends on what your event handler does, but I'm assuming that you don't want it to be called multiple times.
There is no problem in unsubscribing from an event that you haven't subscribed to.
So if you're not sure what state your application is in (though you really should be) you can have:
a.SomethingChanged -= ChangeHandler;
...
a.SomethingChanged += ChangeHandler;
(Note: the new EventHandler(...) is syntactic sugar and can be omitted)
Is there a problem if I subscribe to the same event three times with the eventHandler?
Nope, it will just add the event handler three times.
Does this cause ChangeHandler to be invoked 3 times instead of 1?
Yes.
What is best way to handle this?
That depends on what you want; which you haven't specified. If you want a way to add an event handler if and only if it hasn't already been added, then just remove the event handler and then add it again:
a.SomethingChanged -= new EventHandler(ChangeHandler);
a.SomethingChanged += new EventHandler(ChangeHandler);
Is there an issue with unsubscribing from an event that is not registered?
No, it will just do nothing.
I guess C# eventhandler has a list of listeners and it loops thru the list when sending a message. My question is how does this works in internally. Does it make a copy of the list before looping it thru and if so, what happens if someone unregister itself after the list has been copied but it has not yet received the message.
Will it still get the message even do it has unregister itself?
A delegate is immutable, so when you are invoking a delegate the list of subscribers is known and fixed. Subscribing or unsubscribing replaces the delegate that underpins the event.
This does indeed mean that in a multi-threaded scenario you can receive an event after unsubscribing, because either:
the delegate was already in the process of being invoked
a snapshot of the delegate had already been obtained for the purpose of invoking
by 2, I mean the usual pattern (to prevent a null-ref during invoke):
var handler = SomeEvent;
// <===== another thread could unsubscribe at this point
if(handler != null) handler(sender, args); // <== or part way through this invoke
// (and it either case, have the event trigger even though they think they have
// unsubscribed)
For that reason, if you are coding complex multi-threaded code with events, you should code defensively such that the event firing after you think you have unsubscribed is not a problem.
These nuances do not really impact single-threaded code.
Here is my question: if I want to ensure, that a handler is subscribed only once, is it correct to subscribe in this way:
x.Event -= Handler;
x.Event += Handler;
Idea is "try unsubscribe, even if we were not subscribed", then subscribe when we are 100% not subscribed.
Is this idea correct, and if not - why? Googled it for some time, cannot seem to find the answer myself.
So long as you do that everywhere you're subscribing that handler, it should be fine. But if you subscribe 100 times and then run that code, you're still going to be left with 100 subscriptions.
(I'm assuming you're only using a single thread, by the way. There's a race condition if two threads execute that code at the same time... they could both unsubscribe an then both subscribe, leaving two active subscriptions.)
What you have will not throw any exceptions, so it will work as intended -- but it's not very clear code.
I would very much prefer a test with a boolean flag instead:
if(!subscribed) {
x.Event += Handler;
}