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

心不动则不痛 提交于 2020-01-03 08:44: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?


回答1:


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?




回答2:


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)


来源:https://stackoverflow.com/questions/16711254/how-to-check-for-subscribers-before-raising-an-event-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!