SoFunction
Updated on 2025-03-07

C# implements publish and subscribe mode based on custom event EventArgs

1. Event parameters

    //Event Parameters    class CustomEventArgs:EventArgs
    {
        public CustomEventArgs( string message)
        {
            Message = message;
        }
        public string Message { get; set; }
    }

2. Event Publisher

    //Event Publisher: The definition and call of the event, and the triggering event can also be written here.    class Publisher
    {
        public event EventHandler<CustomEventArgs> CustomEvent;

        public void DoSomething()
        {
            //You can write some other things here before calling
            //
            OnCustomEvent(new CustomEventArgs("I am event parameter"));
        }

        //Package the call of the event in the protected virtual method, which allows the derived class to override the call behavior        protected virtual void OnCustomEvent(CustomEventArgs e)
        {
            CustomEvent?.Invoke(this, e);
        }
    }

3. Event subscribers

    // Event Subscriber: Event Method Writing and Subscription Function    class Subscriber
    {
        private readonly string Str;
        ////The subscribe action must be here, so it must be transmitted to the publisher        public Subscriber( string str,Publisher publisher)
        {
            Str = str;
            //Subscribe to events             += HanderCustomEvent;
        }

        private void HanderCustomEvent(object sender, CustomEventArgs e)
        {
            //Do what you want to do here            ($"Published by:{()},Subscribers:{Str},The parameters are:{}");
        }
    }

    // Event Subscriber: Event Method Writing and Subscription Function    class Subscriber2
    {
        private readonly string Str;
        ////The subscribe action must be here, so it must be transmitted to the publisher        public Subscriber2(string str, Publisher publisher)
        {
            Str = str;
            //Subscribe to events             += HanderCustomEvent;
        }

        private void HanderCustomEvent(object sender, CustomEventArgs e)
        {
            //Do what you want to do here            ($"Published by:{()},Subscribers:{Str},The parameters are:{}");
        }
    }

4. Call events

        static void Main(string[] args)
        {
            Publisher publisher = new Publisher();
            Subscriber subscriber1 = new Subscriber("subscriber1", publisher);
            Subscriber2 subscriber2 = new Subscriber2("subscriber2", publisher);
            //Calling the method that raises the event            ();

            ();
        }

This is all about this article about C# implementing the publish subscription model based on custom event EventArgs. I hope it will be helpful to everyone's learning and I hope everyone will support me more.