How to implement a cancel event in C#

后端 未结 5 1544
星月不相逢
星月不相逢 2021-02-12 12:28

I know that in C#, there are several built in events that pass a parameter (\"Cancel\") which if set to true will stop further execution in the object that raised the eve

5条回答
  •  名媛妹妹
    2021-02-12 13:12

    What I needed was a way to stop the subscribers from receiving the event after a subscriber canceled it. In my situation I don't want the event to further propagate to the other subscribers after some subscriber canceled it. I have implemented this using custom event handling:

    public class Program
    {
        private static List> SubscribersList = new List>();
    
        public static event EventHandler TheEvent
        {
            add {
                if (!SubscribersList.Contains(value))
                {
                    SubscribersList.Add(value);
                }
            }
            remove
            {
                if (SubscribersList.Contains(value))
                {
                    SubscribersList.Remove(value);
                }
            }
        }
    
        public static void RaiseTheEvent(object sender, CancelEventArgs cancelArgs)
        {
            foreach (EventHandler sub in SubscribersList)
            {
                sub(sender, cancelArgs);
    
                // Stop the Execution after a subscriber cancels the event
                if (cancelArgs.Cancel)
                {
                    break;
                }
            }
        }
    
    
        static void Main(string[] args)
        {
            new Subscriber1();
            new Subscriber2();
    
            Console.WriteLine("Program: Raising the event");
    
            CancelEventArgs cancelArgs = new CancelEventArgs();
            RaiseTheEvent(null, cancelArgs);
            if (cancelArgs.Cancel)
            {
                Console.WriteLine("Program: The Event was Canceled");
            }
            else
            {
                Console.WriteLine("Program: The Event was NOT Canceled");
            }
            Console.ReadLine();
        }
    }
    
    public class Subscriber1
    {
        public Subscriber1()
        {
            Program.TheEvent += new EventHandler(program_TheEvent);
        }
    
        void program_TheEvent(object sender, CancelEventArgs e)
        {
            Console.WriteLine("Subscriber1: in program_TheEvent");
            Console.WriteLine("Subscriber1: Canceling the event");
            e.Cancel = true;
        }
    }
    
    public class Subscriber2
    {
        public Subscriber2()
        {
            Program.TheEvent += new EventHandler(program_TheEvent);
        }
    
        void program_TheEvent(object sender, CancelEventArgs e)
        {
            Console.WriteLine("Subscriber2: in program_TheEvent");
    
        }
    }
    

提交回复
热议问题