Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading;
- // Define a class to hold custom event info
- public class CustomEventArgs : EventArgs
- {
- public CustomEventArgs(string s)
- {
- info = s;
- }
- private string info;
- public string Info
- {
- get { return info; }
- set { info = value; }
- }
- }
- // Class that publishes an event
- class Publisher
- {
- //Event that using above class
- public event EventHandler<CustomEventArgs> RaiseCustomEvent;
- public void DoSomething()
- {
- // Write some code that does something useful here
- // then raise the event. You can also raise an event
- // before you execute a block of code.
- OnRaiseCustomEvent(new CustomEventArgs("Help!!!"));
- Thread.Sleep(2000);
- //recursion
- DoSomething();
- }
- // Wrap event invocations inside a protected virtual method
- // to allow derived classes to override the event invocation behavior
- protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
- {
- // Make a temporary copy of the event to avoid possibility of
- // a race condition if the last subscriber unsubscribes
- // immediately after the null check and before the event is raised.
- EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
- // Event will be null if there are no subscribers
- if (handler != null)
- {
- e.Info += String.Format(" at {0}", DateTime.Now.ToString());
- // Use the () operator to raise the event.
- handler(this, e);
- }
- }
- }
- class Subscriber
- {
- private string id;
- public Subscriber(string ID, Publisher pub)
- {
- id = ID;
- // Subscribe to the event
- pub.RaiseCustomEvent += HandleCustomEvent;
- }
- // Define what actions to take when the event is raised.
- void HandleCustomEvent(object sender, CustomEventArgs e)
- {
- Console.Beep();
- Console.WriteLine("I caught the event!!!");
- Console.WriteLine(e.Info);
- }
- }
- class Program
- {
- static void Main()
- {
- Publisher pub = new Publisher();
- Subscriber sub1 = new Subscriber("sub1", pub);
- // Call the method that raises the event.
- pub.DoSomething();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment