How to check for subscribers before raising an eve

2019-06-18 15:29发布

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?

2条回答
\"骚年 ilove
2楼-- · 2019-06-18 16:02

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?

查看更多
家丑人穷心不美
3楼-- · 2019-06-18 16:16

A direct conversion would be:

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

However RaiseEvent has to be used to raise events in VB.NET, you cannot simply call the 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)
查看更多
登录 后发表回答