Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for subscribers before raising an event in VB.NET

In C#, you do something like this:

if (Changed != null)
    Changed(this, EventArgs.Empty);

But what do you do in VB.NET?

There is RaiseEvent, but is

RaiseEvent Changed(Me, EventArgs.Empty)

actually checking that something has subscribed to the event?

like image 957
Sacha K Avatar asked May 23 '13 10:05

Sacha K


1 Answers

Unlike its C# equivalent, RaiseEvent in VB.NET will not raise an exception if there are no listeners, so it is not strictly necessary to perform the null check first.

But if you want to do so anyway, there is a syntax for it. You just need to add Event as a suffix to the end of the event's name. (If you don't do this, you'll get a compiler error.) For example:

If ChangedEvent IsNot Nothing Then
    RaiseEvent Changed(Me, EventArgs.Empty)
End If

Like I said above, though, I'm not really sure if there's any real benefit to doing this. It makes your code non-idiomatic and more difficult to read. The trick I present here isn't particularly well-documented, presumably because the whole point of the RaiseEvent keyword is to handle all of this for you in the background. It's much more convenient and intuitive that way, two design goals of the VB.NET language.

Another reason you should probably leave this to be handled automatically is because it's somewhat difficult to get it right when doing it the C# way. The example snippet you've shown actually contains a race condition, a bug waiting to happen. More specifically, it's not thread-safe. You're supposed to create a temporary variable that captures the current set of event handlers, then do the null check. Something like this:

EventHandler tmp = Changed;
if (tmp != null)
{
    tmp(this, EventArgs.Empty);
}

Eric Lippert has a great blog article about this here, inspired by this Stack Overflow question.

Interestingly, if you examine disassembled VB.NET code that utilizes the RaiseEvent keyword, you'll find that it is doing exactly what the above correct C# code does: declares a temporary variable, performs a null check, and then invokes the delegate. Why clutter up your code with all this each time?

like image 101
Cody Gray Avatar answered Sep 22 '22 22:09

Cody Gray