GetInvocationList events in VB.NET

I am trying to learn some of the principles of WCF by following the example WCF application (from Sacha Barber).

Now I would like to convert the following function to VB.NET

private void BroadcastMessage(ChatEventArgs e) { ChatEventHandler temp = ChatEvent; if (temp != null) { foreach (ChatEventHandler handler in temp.GetInvocationList()) { handler.BeginInvoke(this, e, new AsyncCallback(EndAsync), null); } } } 

but I have some problems because the following code is not accepted by the compiler

 Private Sub BroadcastMessage(ByVal e As ChatEventArgs) Dim handlers As EventHandler(Of ChatEventArgs) = ChatEvent If handlers IsNot Nothing Then For Each handler As EventHandler(Of ChatEventArgs) In handlers.GetInvocationList() handler.BeginInvoke(Me, e, New AsyncCallback(AddressOf EndAsync), Nothing) Next End If End Sub 

it says

A public ChatEvent event (sender Like Object, e As ChatEventArgs) is an event and cannot be called directly

Approaching the point, is it possible in VB.NET to get handlers associated with a certain event in some other way?

+7
events delegates
source share
2 answers

use ChatEventEvent (or EventNameEvent)

It will not appear in intellisense, but its members will.

VB.NET creates a variable behind the scenes to hide complexity from the encoder ...

This is only available in the class declaring the event (or perhaps its descendants)

+7
source share

You are probably trying to write this code in a class that is a descendant of a class that declares a ChatEvent event. This is not possible because events can only be considered as variables (including their invocation) in the class that declares them. This is because the event keyword actually tells the compiler that it needs to perform some behind-the-scenes conversions.

What's happening

Consider this expression:

 Public Event MyEvent as EventHandler 

Simple enough, right? However, this actually happens (you just don't see it)

 Private compilerGeneratedName as EventHandler Public Event MyEvent as EventHandler AddHandler(ByVal value as EventHandler) compilerGeneratedName += value End AddHandler RemoveHandler(ByVal value as EventHandler) compilerGeneratedName -= value End RemoveHandler RaiseEvent(ByVal sender as Object, ByVal e as EventArgs) compilerGeneratedName.Invoke(sender, e) End RaiseEvent End Event 

And when you trigger the event:

 RaiseEvent MyEvent(Me, EventArgs.Emtpy) 

It actually calls the code in a RaiseEvent block.

Edit

If events in VB.NET cannot be considered variables anywhere (they can be considered variables in a declaring class in C #, so your C # example compiles), then you have to explicitly implement the event yourself. For more information on how to do this, see Page

+5
source share

All Articles