Question Managed How to use managed callback?

bsaucer

New member
Joined
Oct 3, 2008
Messages
3
Programming Experience
5-10
I am writing classes in VB.Net (both managed). The main class "A" creates an instance of "B". Class "B" must call a method of Class "A". I need to know two things (syntax, etc...):

1. How does class "A" tell class "B" what method to call?
2. How does class "B" call the method?

The method must pass back an array of Shorts (in this particular example), either as a return value, or as a ByRef argument.

I don't want to use an event if I don't have to. The execution is timing critical. (I assume event handling involves a lot of overhead by the operating system, but I may be wrong.)
 
If you're writing classes in VB.NET then there's no possibility of they're not managed. .NET code is managed code.

As for the question, the answer is that you use a delegate. Delegates are types, just like classes. You can think of delegates as special classes that have a single property that refers to a method rather than an object. There are lots of delegates already declared in the .NET Framework so you can use one of them or, if there isn't a suitable option, declare one yourself. Your first options will be an Action, which doesn't return anything and has up to four parameters (in .NET 4.0 that has increased to 16) or a Func, which does return something and also has up to four parameters.

You create a delegate object using the AddressOf operator. Once you've got the object, you treat it like any other object. It can be passed around and assigned to fields, properties, method parameters, etc, just like any other object. When you're ready to execute the method, you call the Invoke method of the delegate and pass the appropriate arguments.

So, assuming that the method needs to take no arguments and return a Short array , you could use a Func(Of Short()) delegate. Class B needs some way to accept a Func(Of Short()) object. Like for any other object, that would involve a constructor parameter or a property of that type or both. Class A would then use the AddressOf operator to create the delegate referring to a method with the appropriate signature. Class A passes the object to class B and class B stores it wherever, e.g. a member variable, and then calls Invoke on it when appropriate.
 
Back
Top