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

In C #, you are doing something like this:

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

But what are you doing in VB.NET?

There is a RaiseEvent , but

 RaiseEvent Changed(Me, EventArgs.Empty) 

check that something has subscribed to this event?

+6
source share
2 answers

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

But if you still want to do this, there is syntax for it. You just need to add Event as a suffix to the end of the event name. (If you do not, you will get a compiler error.) For example:

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

As I said above, I'm not sure if there is any real benefit to this. This makes your code non-idiomatic and more difficult to read. The trick I present here is not particularly well documented, apparently because the whole point of the RaiseEvent should handle all this for you in the background. This is much more convenient and intuitive, since the two design goals are in VB.NET.

Another reason you should probably leave this automatically is that it is hard to do it right when you do this in C #. The example fragment that you actually showed contains a race condition that expects an error. More specifically, it is not thread safe. You must create a temporary variable that captures the current set of event handlers and then performs a null check. Something like that:

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

Eric Lippert has a wonderful blog article about it here , inspired by this question .

Interestingly, if you examine the disassembled VB.NET code that uses the RaiseEvent keyword, you will find that it does exactly what the correct C # code does: declares a temporary variable, performs a null check, and then calls the delegate. Why clutter your code every time?

+11
source

Direct conversion:

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

However, RaiseEvent must be used to raise events in VB.NET, you cannot just raise an event. No exception is thrown using RaiseEvent if there are no listeners.

See: http://msdn.microsoft.com/en-GB/library/fwd3bwed(v=vs.71).aspx

Therefore, the following should be used:

 RaiseEvent Changed(Me, EventArgs.Empty) 
+2
source

Source: https://habr.com/ru/post/945669/


All Articles