There's normally two part of this mechanism. one is publish and second is subscriber.
One publish have multiple subscribers. publish also unaware of number of subscribers.
Sample Code to Understand Creting and Subscribing to new events
namespaceConsoleAppTest{internalstaticclassProgram{privatestaticvoidMain(){varvideo=newVideo{Title="Video 1"};varvideoEncoder=newVideoEncoder();varmailService=newMailService();videoEncoder.VideoEncoded+=mailService.OnVideoEncode;videoEncoder.Encode(video);Console.WriteLine("Press Any key to continue");Console.ReadLine();}}publicclassVideo{publicstringTitle{get;set;}}publicclassVideoEncoder{//1.Define Delegate//Naming of Delegage = NameOfDelgate + postfix(EventHandler)publicdelegatevoidVideoEncodedEventHandler(objectsource,EventArgsargs);//2.Define an event based on that delegatepubliceventVideoEncodedEventHandlerVideoEncoded;//3.Raise the eventprotectedvirtualvoidOnVideoEncoded(){if(VideoEncoded!=null){VideoEncoded(this,EventArgs.Empty);}}publicvoidEncode(Videovideo){Console.WriteLine("Encoding Video...");Thread.Sleep(3000);OnVideoEncoded();}}publicclassMailService{publicvoidOnVideoEncode(objectsource,EventArgse){Console.WriteLine("Sending Mail...");}}}
Events which also pass some info to it's subscribers
namespaceConsoleAppTest{internalstaticclassProgram{privatestaticvoidMain(){varvideo=newVideo{Title="Video 1"};varvideoEncoder=newVideoEncoder();varmailService=newMailService();videoEncoder.VideoEncoded+=mailService.OnVideoEncode;videoEncoder.Encode(video);Console.WriteLine("Press Any key to continue");Console.ReadLine();}}publicclassVideo{publicstringTitle{get;set;}}publicclassVideoEventArgs:EventArgs{publicVideoVideo{get;set;}}publicclassVideoEncoder{//1.Define Delegate//Naming of Delegage = NameOfDelgate + postfix(EventHandler)publicdelegatevoidVideoEncodedEventHandler(objectsource,VideoEventArgsargs);//2.Define an event based on that delegatepubliceventVideoEncodedEventHandlerVideoEncoded;//3.Raise the eventprotectedvirtualvoidOnVideoEncoded(Videovideo){if(VideoEncoded!=null){VideoEncoded(this,newVideoEventArgs(){Video=video});}}publicvoidEncode(Videovideo){Console.WriteLine("Encoding Video...");Thread.Sleep(3000);OnVideoEncoded(video);}}publicclassMailService{publicvoidOnVideoEncode(objectsource,VideoEventArgse){Console.WriteLine("Sending Mail..."+e.Video.Title);}}}
Use Inbuilt Delegated instead of creating own
publicclassVideoEncoder{//2.Define an event based on that delegate//we can use EventHandler if we don't need to pass any datapubliceventEventHandler<VideoEventArgs>VideoEncoded;//3.Raise the eventprotectedvirtualvoidOnVideoEncoded(Videovideo){if(VideoEncoded!=null){VideoEncoded(this,newVideoEventArgs(){Video=video});}}publicvoidEncode(Videovideo){Console.WriteLine("Encoding Video...");Thread.Sleep(3000);OnVideoEncoded(video);}}