Multicast event

You can multicast in an event in the same way that you can in a delegate. This means that you can register multiple event handlers (methods that have subscribed to the event) to an event and all of them will be executed one by one when the event gets fired. To multicast, you have to use the += sign to register event handlers to the event. You can also remove event handlers from the event by using the -= operator. When you apply multicast, the first event handler that was registered will get executed first, then the second, and so on. By multicasting, you can easily extend or reduce event handlers in your application without doing much work. Let's look at an example of multicasting:

using System;

namespace EventsAndDelegates
{
public delegate void GetResult();

public class ResultPublishEvent
{
public event GetResult PublishResult;

public void PublishResultNow()
{
if (PublishResult != null)
{
Console.WriteLine("");
Console.WriteLine("We are publishing the results now!");
Console.WriteLine("");
PublishResult();
}
}
}

public class EmailEventHandler
{
public void SendEmail()
{
Console.WriteLine("Results have been emailed successfully!");
}
}

public class SmsEventHandler
{
public void SmsSender()
{
Console.WriteLine("Results have been messaged successfully!");
}
}

public class Program
{
public static void Main(string[] args)
{
ResultPublishEvent e = new ResultPublishEvent();

EmailEventHandler email = new EmailEventHandler();
SmsEventHandler sms = new SmsEventHandler();

e.PublishResult += email.SendEmail;
e.PublishResult += sms.SmsSender;

e.PublishResultNow();

e.PublishResult -= sms.SmsSender;

e.PublishResultNow();

Console.ReadLine();
}
}
}

The following is the output of the preceding code:

Now if we analyze the preceding code, we can see that we have created another class, SmsEventHandler, and this class has a method called SmsSender, which follows the same signature as our delegate GetResult, as shown in the following code:

public class SmsEventHandler
{
public void SmsSender()
{
Console.WriteLine("Results have been messaged successfully!");
}
}

Then, in the main method, we create an instance of this SmsEventHandler class and register the SmsSender method to the event, as shown in the following code:

e.PublishResult += sms.SmsSender;

After firing the event once, we remove the SmsSender event handler from the event using the -= operator, as follows:

e.PublishResult -= sms.SmsSender;

When we fire the event again, we can see in the output that only the email event handler was executed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.229.143