I've just encountered a bug in the program I'm writing where an exception was thrown stating an "object reference must be set to an instance of an object". Upon investigation, I found that this exception was thrown when trying to fire an event BUT the event didn't have any delegate methods added to it.
I wanted to check that my understanding was correct that as a developer you shouldn't fire events without first checking that the event doesn't equal null? For example:
if (this.MyEventThatIWantToFire != null)
{
this.MyEventThatIWantToFire();
}
Thanks in advance for the advice/thoughts.
The pattern you've shown is broken in a multi-threaded environment. MyEventThatIWantToFire could become null after the test but before the invocation. Here's a safer approach:
EventHandler handler = MyEventThatIWantToFire;
if (handler != null)
{
handler(...);
}
Note that unless you use some sort of memory barrier, there's no guarantee you'll see the latest set of subscribers, even ignoring the obvious race condition.
But yes, unless you know that it will be non-null, you need to perform a check or use a helper method to do the check for you.
One way of making sure there's always a subscriber is to add a no-op subscriber yourself, e.g.
public event EventHandler MyEventThatIWantToFire = delegate {};
Of course, events don't have to be implemented with simple delegate fields. For example, you could have an event backed by a List<EventHandler> instead, using an empty list to start with. That would be quite unusual though.
An event itself is never null, because the event itself is just a pair of methods (add/remove). See my article about events and delegates for more details.
You shouldn't do it that way - if someone where to remove a listener between the if and the call to the event, you'd get an exception. It is good practise to use it with a local variable:
protected void RaiseEvent()
{
var handler = Event;
if(handler != null)
handler(this, EventArgs.Empty);
}
Of course, this has the disadvantage of maybe calling a listener that already was removed between the creation of the local variable and the call to the handler.
Yes, you should check it for null but the way you're doing it leads to a race condition. It's possible the event may end up being null anyway if someone unsubscribes the last delegate in between your "if" and your event raise. The accepted way to do this is like:
var temp = this.MyEventThatIWantToFire;
if (temp != null) {
this.temp(this, EventArgs.Empty);
}
or alternatively, ensure there's always at least one delegate in the invocation list by declaring your event like this:
public event EventHandler MyEventThatIWantToFire = delegate {};
Make sense?
Yes, your understanding is correct. It's up to you to check the delegate's value before calling it.
Most delegates - which events are - are "multi-cast" delegates. This means that a delegate can manage a list of one or more methods that it will call when activated.
When the delegate evaluates to a null value, there are no registered methods; therefore, there is nothing to call. If it evaluates to something other than a null value, there is at least one method registered. Calling the delegate is an instruction to call all methods it has registered. The methods are called in no guaranteed order.
Using the addition-assignment operator (+=) or addition operator (+) adds a method to the delegate's list of methods. Using the subtraction-assignment operator (-=) or subtraction operator (-) removes a method from the delegate's list of methods.
Also note that the called methods are executed from the caller's thread. This is important if you are using events to update your user interface controls. In this situation, use of your control's InvokeRequired property lets you handle cross-threading calls (using Invoke() or BeginInvoke()) gracefully.
Yes in C# if an event has no delegates, it will be null, so you must check
Yes, you must check whether event is not null. Mostly you encounter protected method that does the check and invokes event, or even constructs event args. Something like this:
public event EventHandler Foo;
protected void OnFoo() {
if (Foo == null)
return;
Foo(this, new EventArgs());
}
This approach also alows your derived classes to invoke (or prevent invoking) the event.
Related
I have a static class to handler MS SQL database interaction with an eventhandler like this:
public static event EventHandler<SQLExceptionEventArgs> SQLExceptionCaught;
then I have a function to handle it:
private static void OnSQLExceptionCaught(SqlException e)
{
if (SQLExceptionCaught != null)
{
SQLExceptionCaught(SQLExceptionCaught.Target, new SQLExceptionEventArgs(e));
}
}
I also have a custom form inherited from Windows.Forms.Form which adds a delegate to that event handler:
DBHandler.SQLExceptionCaught += this.handleSQLException;
(it's removed when form is closing)
and then this delegate is overriden in each form.
It works fine when only one form is open, but I cannot make it work for multiple forms so it only fires the delegate from the form that actually fired the event.
Would you please point me to the right direction on that? Is it even possible?
I'd gladly consider any other solution as long as it preserve this functionality.
It sounds to me like you should turn your static class into a non-static class. Then you'd have an instance event, and two instances of the class (one per form). At that point, the two event handlers would be appropriately separated. Fundamentally, you're sharing inappropriately at the moment.
As an aside, your current code can throw a NullReferenceException due to the value of SQLExceptionCaught becoming null after the check but before the next line. Typically you'd fix this using a local variable:
private static void OnSQLExceptionCaught(SqlException e)
{
var handler = SQLExceptionCaught;
if (handler != null)
{
handler(SQLExceptionCaught.Target, new SQLExceptionEventArgs(e));
}
}
There are other options around extension methods and the null conditional operator introduced in C# 6... see my blog post on the topic for more details.
You could find the problem as folows:
Open multiple forms.
Set a breakpoint in your OnSQLExceptionCaught.
At that point, check the content of the event SQLExceptionCaught, using the method GetInvocationList. If it has only one form as a subscriber, check your code which is subscribing to your event.
It there are more than one subscribers, and only one subscriber is called, make sure that subscriber does NOT throw an exception. If an exception is thrown during the invocation of an event, the other subscribers are not getting called.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a downside to adding an anonymous empty delegate on event declaration?
The following pattern is quite common when using event handlers (in C#):
public event Action handler;
…
// some method:
if(handler != null) handler();
Are there any downsides of assigning an empty delegate to this event? This would save the if !=null condition everywhere, where the event is fired. Of course, this only applies, when the we cannot guarantee that the event is always assigned a proper delegate.
public event Action handler;
…
// in constructor:
handler += ()=>{};
…
// some method:
handler();
Sure, there's a slight performance hit, but it makes the code much cleaner. What's the best practice in such a case? Any technical disadvantages?
Interesting idea, I've never thought of doing that. The way i do my custom events is i make a OnCustomEventName taking parameters for the event and just do the check in there for null. and call OnCustomEventName from the code wherever i want the event triggered from.
Avoids any performance hits and keeps the operational code cleaner than a 2-line if check every time you want the event fired.
That being said this isn't answering the question about technical disadvantages but more of a best practice when firing events.
example code for threadsafe "On" function.
private void OnCustomEventName()
{
DelegateName localhandler = CustomEventName;
if (localhandler != null)
localhandler();
}
Instead of adding an empty delegate in the constructor, you can wrap the handler in a function which first checks if the handler is null then calls it. The downside of this is if you have a lot of events, you will have a lot of functions that wrap each event.
private void HandlerWrapper()
{
Action localHandler = handler;
if (localHandler != null) handler();
}
I haven't really found any big downsides to do this and generally I prefer it over checking for null. The only issue I cant think of is that it might lead to annoying steps in the code when debugging (i.e.
having to step over the empty delegate whenever stepping into an event).
I think that performance isn't an issue - if application performance degenerates significantly by invoking events, the event should probably not have been there in the first place.
public class TestA
{
public event Action<int> updateEvent;
...
if(updateEvent != null)
{
Actin<int> tempEvent = updateEvent;
updateEvent(1);
}
}
public class TestB
{
public Action<int> updateEvent;
...
if(updateEvent != null)
{
Actin<int> tempEvent = updateEvent;
updateEvent(1);
}
}
however event Action<T> is eventQueue au
use same and resutl same. What is more good? (i like TestB. Because simple using.)
The event modifier is useful to prevent an assignment. What does it mean? If that's a callback with many handlers attached you may want to prevent that someone simply write:
myObject.UpdateEvent = null or something like that. With event they can't do that. Take a look at Learning C# 3.0: Master the fundamentals of C# 3.0.
The code you use to call the event isn't bad but not so useful, if you assign the delegate to temporary variable you may want to be somehow thread-safe (someone could unhook after your null check) so you should do it before the check:
Action<int> tempEvent = updateEvent;
if (tempEvent != null)
tempEvent(1);
A little side note: if you use events you may want to follow .NET Framework patterns and guidelines, take a look at MSDN
To the compiler, the difference is that the event cannot be invoked except by the declaring class (like a private member). You can use either in the same way.
To design, events should represent their namesake, i.e. events. Think of a Delegate as just the type or signature of methods. You would declare a class to have an event (of type Action), and you would add (subscribe) to that event other Actions (or methods that can be cast to an Action).
Furthermore, it is common practice to create events of a type that inherits from EventHandler<T>
An event is just a delegate with some access wrappers.
The problem with your TestB is that because the updateEvent delegate is public, ANYONE can fire the delegate, not just the class owning it.
Defining it as an Event as in your TestA, client code can only subscribe or unsubscribe to the event, they cannot fire it.
ps. You do not need your tempEvent delegates.
In answer to my other question How to send custom event message just after control instantiation? I read this:
if (ValueChanged != null)
{
ValueChanged(sender, e);
}
What is ValueChanged in the first case ? Not a function as in the second instruction ? How can the same symbol be used for both ... and function ?
uPDATE after james's answer: if ValueChanged is an Object, How can I call it as if it were a Method? Is it a syntactic sugar or alien syntax with some mysterious mechanism behind like calling ValueChanged.Invoke(sender, e); ?
ValueChanged is a multi-cast delegate, which is an object. If no one has subscribed to the event, it can be null, hence the check. If you want to avoid the check, you can define an empty delegate and assign it to the event.
public event EventHandler ValueChanged = delegate {};
You can now just call ValueChanged(sender, e) because ValueChanged can never be null.
Like many things in C# there are language features designed to make things easier. Think of ValueChanged as a field and that you check that it is null (internally the delegate will check for subscribers) and the second a shorthand version of
ValueChanged.Invoke(sender, e);
The actual signature of the event is more than a field of course. It exposes a public add/remove property for subscribers as well as a private field for invoking.
ValueChanged is the same in both cases.
First, you check if it is null, which will be the case if there are no subscribers.
Second, you execute the delegate using method-like syntax.
Events are just delegates - a reference to a function elsewhere. When invoking an event like above, we are calling the delegate. Since the delegate is just a reference to a function, we need to handle the case where it may not have been set previously (I.E. null)
ValueChanged is a reference to one or more functions. If there are no references, then the value will be null. If the value is not null, then all of the referenced functions will called by the ValueChanged(sender, e); syntax.
This seems odd to me -- VB.NET handles the null check implicitly via its RaiseEvent keyword. It seems to raise the amount of boilerplate around events considerably and I don't see what benefit it provides.
I'm sure the language designers had a good reason to do this.. but I'm curious if anyone knows why.
It's certainly a point of annoyance.
When you write code which accesses a field-like event within a class, you're actually accessing the field itself (modulo a few changes in C# 4; let's not go there for the moment).
So, options would be:
Special-case field-like event invocations so that they didn't actually refer to the field directly, but instead added a wrapper
Handle all delegate invocations differently, such that:
Action<string> x = null;
x();
wouldn't throw an exception.
Of course, for non-void delegates (and events) both options raise a problem:
Func<int> x = null;
int y = x();
Should that silently return 0? (The default value of an int.) Or is it actually masking a bug (more likely). It would be somewhat inconsistent to make it silently ignore the fact that you're trying to invoke a null delegate. It would be even odder in this case, which doesn't use C#'s syntactic sugar:
Func<int> x = null;
int y = x.Invoke();
Basically things become tricky and inconsistent with the rest of the language almost whatever you do. I don't like it either, but I'm not sure what a practical but consistent solution might be...
we usually work around this by declaring our events like this:
public event EventHandler<FooEventArgs> Foo = delegate { };
this has two advantages. The first is that we don't have check for null. The second is that we avoid the critical section issue that is omnipresent in typical event firing:
// old, busted code that happens to work most of the time since
// a lot of code never unsubscribes from events
protected virtual void OnFoo(FooEventArgs e)
{
// two threads, first checks for null and succeeds and enters
if (Foo != null) {
// second thread removes event handler now, leaving Foo = null
// first thread resumes and crashes.
Foo(this, e);
}
}
// proper thread-safe code
protected virtual void OnFoo(FooEventArgs e)
{
EventHandler<FooEventArgs> handler = Foo;
if (handler != null)
handler(this, e);
}
But with the automatic initialization of Foo to an empty delegate, there is never any checking necessary and the code is automatically thread-safe, and easier to read to boot:
protected virtual void OnFoo(FooEventArgs e)
{
Foo(this, e); // always good
}
With apologies to Pat Morita in the Karate Kid, "Best way to avoid null is not have one."
As to the why, C# doesn't coddle you as much as VB. Although the event keyword hides most of the implementation details of multicast delegates, it does give you finer control than VB.
You need to consider what code would be required if setting up the plumbing to raise the event in the first place would be expensive (like SystemEvents) or when preparing the event arguments would be expensive (like the Paint event).
The Visual Basic style of event handling doesn't let you postpone the cost of supporting such an event. You cannot override the add/remove accessors to delay putting the expensive plumbing in place. And you cannot discover that there might not be any event handlers subscribed so that burning the cycles to prepare the event arguments is a waste of time.
Not an issue in C#. Classic trade-off between convenience and control.
Extension methods provide a very cool way, to get around this. Consider the following code:
static public class Extensions
{
public static void Raise(this EventHandler handler, object sender)
{
Raise(handler, sender, EventArgs.Empty);
}
public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null) handler(sender, args);
}
public static void Raise<T>(this EventHandler<T> handler, object sender, T args)
where T : EventArgs
{
if (handler != null) handler(sender, args);
}
}
Now you can simply do this:
class Test
{
public event EventHandler SomeEvent;
public void DoSomething()
{
SomeEvent.Raise(this);
}
}
However as others already mentioned, you should be aware of the possible race condition in multi-threaded scenarios.
Don't really know why is this done, but there's a variation of a Null Object pattern specifically for delegates:
private event EventHandler Foo = (sender, args) => {};
This way you can freely invoke Foo without ever checking for null.
Because RaiseEvent carries a some overhead.
There's always a tradeoff between control and ease of use.
VB.Net: ease of use,
C#: more control as VB
C++: even more control, less guidance, easier to shoot yourself in the foot
Edit: As the OP points out, this answer does not address the body of the question. However, some may find it useful because it does provide an answer for the title of the question (when taken by itself):
Why does C# require you to write a null check every time you fire an event?
It also provides context for the intent of the body of the question which some may find useful. So, for those reasons and this advice on Meta, I'll let this answer stand.
Original Text:
In its MSDN article How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide) ( Visual Studio 2013), Microsoft includes the following comment in its example:
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
Here is a larger excerpt from Microsoft's example code that gives context to that comment.
// Wrap event invocations inside a protected virtual method
// to allow derived classes to override the event invocation behavior
protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
// Event will be null if there are no subscribers
if (handler != null)
{
// Format the string to send inside the CustomEventArgs parameter
e.Message += String.Format(" at {0}", DateTime.Now.ToString());
// Use the () operator to raise the event.
handler(this, e);
}
}
Note that as of C# 6, the language now provides a concise syntax to perform this null check conveniently. E.g.:
public event EventHandler SomeEvent;
private void M()
{
// raise the event:
SomeEvent?.Invoke(this, EventArgs.Empty);
}
See Null Conditional Operator
The reason really boils down to C# giving you more control. In C# you do not have to do the null check if you so choose. In the following code MyEvent can never be null so why bother doing the check?
public class EventTest
{
private event EventHandler MyEvent = delegate { Console.WriteLine("Hello World"); }
public void Test()
{
MyEvent(this, new EventArgs());
}
}