Page 1 of 1

custom events in C# IDL must always have at least one client

Posted: Thu Aug 31, 2006 3:26 am
by michal.kreslik
Hello,

I have just found the custom event needs to have at least one client registered to consume the event or else the application (in this case the IDL indicator) will "crash quietly" - the rest of the method's code where the event-firing statement occurs will be skipped without you knowing what's going on.

Evidence - test bench program:

Code: Select all

using System;

namespace EventsTest
{
    public delegate void FirstEventHandler();
    public delegate void SecondEventHandler();

    public class EventsClass
    {
        public event FirstEventHandler FirstEvent;
        public event SecondEventHandler SecondEvent;

        private void FireOffFirstEvent()
        {
            FirstEvent();
        }

        private void FireOffSecondEvent()
        {
            SecondEvent();
        }

        public void FireOffAllEvents()
        {
            FireOffFirstEvent();
            FireOffSecondEvent();
        }
    }

    public class EntryClass
    {
        static void Main()
        {
            EventsClass MyEvents = new EventsClass();
            string MyChoice;

            do
            {
                Console.Write("Do you wish to register the event clients to the events? (y/n): ");
                MyChoice = Console.ReadLine();

            } while (MyChoice != "y" && MyChoice != "n");

            switch (MyChoice)
            {
                case "y":

                    MyEvents.FirstEvent += new FirstEventHandler(FirstEventClient);
                    Console.WriteLine("First event registered.");

                    MyEvents.SecondEvent += new SecondEventHandler(SecondEventClient);
                    Console.WriteLine("Second event registered.");

                    break;

                case "n":

                    Console.WriteLine("No events registered.");

                    break;
            }

            Console.WriteLine("Firing off all events..");

            MyEvents.FireOffAllEvents();

            Console.WriteLine("Press enter to continue..");
            Console.ReadLine();
        }

        static void FirstEventClient()
        {
            Console.WriteLine("First event processed successfully.");
        }

        static void SecondEventClient()
        {
            Console.WriteLine("Second event processed successfully.");
        }
    }
}


C# source and compiled exe attached below.

Michal