C#–Using a delegate to raise an event from one class to another

Even though this may be a relatively common task for many people, I’ve had to show it to enough new developers that I figured I’d immortalize it…

MSDN says “Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.” Any time you add a button to a Windows Form or Web app, you can subscribe to the OnClick event, and you can also create your own event handlers to pass events between classes. Here I’ll show you how to raise an event from a separate class to a console application (or Windows Form).

First, create a console app project (you could create a Windows Form, but this is easier for this demo). Add a class file called MyEvent.cs (it doesn’t really need to be a separate file, this is just for clarity) with the following code:

public delegate void MyHandler1(object sender, MyEvent e);

public class MyEvent : EventArgs
{
    public string message;
}

Your event can have whatever public properties you like; here we’re just got a single string.

Next, add a class file called WorkerDLL.cs; this will simulate the class that would be doing all the work in the project. Add the following code:

class WorkerDLL
{
    public event MyHandler1 Event1;

    public WorkerDLL()
    {
    }

    public void DoWork()
    {
        FireEvent("From Worker: Step 1");
        FireEvent("From Worker: Step 5");
        FireEvent("From Worker: Step 10");
    }

    private void FireEvent(string message)
    {
        MyEvent e1 = new MyEvent();
        e1.message = message;

        if (Event1 != null)
        {
            Event1(this, e1);
        }

        e1 = null;
    }
}

Notice that the FireEvent method creates an instance of the MyEvent class and passes it to the Event1 handler (which we’ll create in just a second).

Finally, add the following code to Program.cs:

static void Main(string[] args)
{
    Program p = new Program(args);
}

public Program(string[] args)
{
    Console.WriteLine("From Console: Creating DLL");
    WorkerDLL wd = new WorkerDLL();

    Console.WriteLine("From Console: Wiring up event handler");
    WireEventHandlers(wd);

    Console.WriteLine("From Console: Doing the work");
    wd.DoWork();

    Console.WriteLine("From Console: Done - press any key to finish.");
    Console.ReadLine();
}

private void WireEventHandlers(WorkerDLL wd)
{
    MyHandler1 handler = new MyHandler1(OnHandler1);
    wd.Event1 += handler;
}

public void OnHandler1(object sender, MyEvent e)
{
    Console.WriteLine(e.message);
}

The OnHandler1 method is called any time the event handler “hears” an event matching the specified signature – you could have it log to a file, write to a database, etc. Run the app in debug mode and you should see output like this:

image

You can distinctly see which lines were written by the console application itself (Program.cs) and which were written by the worker class (WorkerDLL.cs).

Technorati Tags:

Print | posted @ Tuesday, June 12, 2012 12:32 PM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: