Tag Archives: event

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

Advertisement