Monday, July 12, 2010

Simple Events Example

This is a short example for how one could use events.

using System;

namespace EventsExample
{
    public class MyEventArgs : EventArgs
    {
        public readonly int Complete;
        public MyEventArgs(int index, int length)
        {
            Complete = (index + 1) * 100 / length;
        }
    }

    public delegate void StartDelegate(object sender, EventArgs e);
    public delegate void UpdateDelegate(object sender, MyEventArgs e);

    public class MyClass
    {
        public event StartDelegate StartEvent;
        public event UpdateDelegate UpdateEvent;

        protected virtual void Start(EventArgs e)
        {
            if (StartEvent != null)
                StartEvent(this, e);
        }

        protected virtual void Update(MyEventArgs e)
        {
            if (UpdateEvent != null)
                UpdateEvent(this, e);
        }

        public void CountTo(int j)
        {
            Start(EventArgs.Empty);
            for (int i = 0; i < j; i++)
            {
                // do stuff here
                Update(new MyEventArgs(i, j));
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.StartEvent += new StartDelegate(myClass_Start);
            myClass.UpdateEvent += new UpdateDelegate(myClass_Update);

            myClass.CountTo(100);
        }

        private static void myClass_Start(object sender, EventArgs e)
        {
            Console.WriteLine("Started!");
        }

        private static void myClass_Update(object sender, MyEventArgs e)
        {
            MyEventArgs f = (MyEventArgs)e;
            Console.WriteLine("{0}% complete", f.Complete);
        }
    }
}

No comments:

Post a Comment