VB.NET Event handling in C#

.NET is a world
of events. Everything happens on a particular event. Today I will try to explain
you events in simple language so that you can use it effectively in your code.

Events can not exist without delegates. A delegate in C#
is similar to a function pointer in C or C++. Using a delegate allows the
programmer to encapsulate a reference to a method inside a delegate object. The
delegate object can then be passed to code which can call the referenced method,
without having to know at compile time which method will be invoked.

Whenever a declared event occurs it publishes itself and all the subscribers to
that event receives notification. There could be n subscribers for an event.

Things
will get clear as we proceed with the example. Follow these steps

This
event will publish itself after every 6 sec. Now in the constructor of this
class we have created a new thread in background which will take care of
publishing this event.

if(OnRespondAfterOneMinute
!= null).

This statement will check after every 6 sec whether there are any subscribers
present for this event or not. If subscribers are present then it will notify
them and will tell them that the event you are interested in have occurred.

Now let see what we need to
do on two windows forms that we have created. These are nothing but the
subscribers for our event.

It
should be noted that the method we are going to execute on this event should
have signature exactly similar to that of the delegate we have declared. So this
function should return void and should not have any parameters in it.

Repeat
this piece of code for listener 2. Now when you will execute this code you can
observe that after every 6 seconds all the listeners who have registered
themselves for this event are getting notification.