How to subscribe to an Event in C# and can we have multiple subscribers to one Event in a C#?

CsharpServer Side ProgrammingProgramming

Events enable a class or object to notify other classes or objects when something of interest occurs.

The class that raises the event is called the publisher and the classes that handle the event are called subscribers.

In the Event

An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

Events that have no subscribers are never raised.

The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.

Example

class Program {
   static void Main() {
      var video = new MP4() { Title = "Eminem" };
      var videoEncoder = new MP4EncoderNew();
      var mailService = new MailService();
      var messageService = new MessageService();
      videoEncoder.mp4Encoded += mailService.onVideoEncoded;
      videoEncoder.mp4Encoded += messageService.onVideoEncoded;
      videoEncoder.Encode(video);
      Console.ReadKey();
   }
}
public class MP4 {
   public string Title { get; set; }
}
public class MP4Args : EventArgs {
   public MP4 mp4 { get; set; }
}
public class MP4EncoderNew {
   public EventHandler mp4Encoded;
   public void Encode(MP4 video) {
      Console.WriteLine("Encoding MP4");
      Thread.Sleep(3000);
      OnVideoEncoded(video);
   }
   protected void OnVideoEncoded(MP4 video) {
      if (mp4Encoded != null) {
         mp4Encoded(this, new MP4Args() { mp4 = video });
      }
   }
}
//Subscriber 1
public class MailService {
   public void onVideoEncoded(object source, MP4Args e) {
      Console.WriteLine("Mail Service:,Sending an email {0}", e.mp4.Title);
   }
}
//Subscriber 2
public class MessageService {
   public void onVideoEncoded(object source, MP4Args e) {
      Console.WriteLine("Message Service:,Sending an Message {0}", e.mp4.Title);
   }
}

Output

Encoding MP4
Mail Service:,Sending an email Eminem
Message Service:,Sending an Message Eminem
raja
Published on 05-Aug-2020 08:51:51
Advertisements