Multicast Delegate

A delegate (object) which simultaneously executes more than one method dynamically can be called as a multicast delegate.

In all of my previous examples, I attached a delegate to one and only one method every time. Now, we are going to assign more than one method to the same delegate. In other words, the moment "invoke()" gets executed, all the methods (addresses of methods) attached to the delegate get executed.

Let us see an example of this:



'multi-cast delegate


Public Class Form7




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)


Dim deleg As Calculate




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


deleg = AddressOf obj.Add


deleg = System.Delegate.Combine(deleg, New Calculate(AddressOf obj.Multiply))


'deleg.Invoke()


deleg()


End Sub


End Class



From the above, the most important lines are the following:



deleg = AddressOf obj.Add


deleg = System.Delegate.Combine(deleg, New Calculate(AddressOf obj.Multiply))



The first line says that the "Add" method must be assigned to the "deleg" object. The second line says that another method, "Multiply," must be assigned to the "deleg" object, to keep existing.

Finally, all the methods in the delegate get executed using the following line:

deleg()

Post a Comment

Previous Post Next Post