Event handling

In this example I created a Worker class that simply does some work. The class sends a Workstarted event right at the beginning of the work task and a closing WorkCompleted event at the end. The WorkStarted event has the standard EventHandler delegate and the WorkCompleted event has an EventHandler<int> delegate (with generic type int) and will return some int value with the event. Every handler subscribing to the event must match the signature, see the WorkStartedEventHandler and WorkCompletedEventHandler Methods.

Worker class, raises the events

using System;
using System.Threading;

namespace EventHandling
{
    public class Worker
    {
        public event EventHandler WorkStarted;
        public event EventHandler<int> WorkCompleted;

        public void Work()
        {
            this.OnWorkStarted();

            // do your task here
            Thread.Sleep(1000);

            this.OnWorkCompleted(42);
        }

        protected virtual void OnWorkStarted()
        {
            this.WorkStarted?.Invoke(this, null);
        }

        protected virtual void OnWorkCompleted(int eventArgInt)
        {
            this.WorkCompleted?.Invoke(this, eventArgInt);
        }
    }
}

Program class, subscribes / registers to the events and handles them

using System;

namespace EventHandling
{
    class Program
    {
        public static void Main(string[] args)
        {
            Worker worker = new Worker();
            worker.WorkStarted += WorkStartedEventHandler;
            worker.WorkCompleted += WorkCompletedEventHandler;

            worker.Work();

            Console.ReadKey();
        }

        private static void WorkStartedEventHandler(object sender, EventArgs args)
        {
            Console.WriteLine("Work started");
        }

        private static void WorkCompletedEventHandler(object sender, int intArg)
        {
            Console.WriteLine($"Work completed, event argument: {intArg}");
        }
    }
}

More links on the subject

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s