sunshine



Events in C#

Events are notifications raised to indicate that something interesting is happened in a software module.

There are 2 parties involved in events. A subscriber who reacts to the event and a Publisher who raises the event. Look at the diagram below.

events

A simple example is a Button Click event in Win Form. The implementer of the Button control, along with all the features like drawing of the control, its color and its ability to change the size when you set the size parameters also implemented the "Click" event as well. The button control is the Publisher here. On your form when you click a button a click event will be fired. So you subscribe to that event and write whatever code you want to happen when the button is clicked.Look at the code below.

class Program

    {

        static void Main(string[] args)

        {

            Form newForm = new Form();

            Button testButton = new Button();

            newForm.Controls.Add(testButton);

            testButton.Click += ButtonClicked;

            newForm.ShowDialog();

        }

        public static void ButtonClicked(object sender, System.EventArgs e)

        {

            MessageBox.Show("hello world");

        }

    }

The above code creates a form and adds a button to it and display it. On the button, we subscribe to the click event. When button is clicked, a message box will be displayed with 'hello world'. The following line

testButton.Click += ButtonClicked;

is interesting. '+=' operator subscribes/wire up the event. Note the 'ButtonClicked' method name after '+='. Basically you are passing a pointer of 'ButtonClicked' method to the testButton. The code in the button controls invoke this method, whenever the user clicks the button. So basically you are passing a pointer of a method in your code to the event raiser and event raiser calls it when right moment comes. If you do not want to listen to this event at a later point use '-=" operator to unsubscribe. Create a console project and copy paste above code and try it out.

Implementing your own event

As you can see, subscribing to an event is easy. Now how do we implement your own event?( in the above example, how do we implement the click event). You can do this by using the 'event' and 'EventHandler' types. Lets do a simple example. The class below implements a very simple event named JobIsAlive. We consume DoSomeWork to get some large work done calling method DoSomeVeryLargeWork. Since it is a long job, time to time this class will fire JobIsAlive event to let the consumer know that this job is still active, wait patiently.

public class DoSomeWork

    {

        public event EventHandler JobIsAlive;



        public void DoSomeVeryLargeWork()

        {

            System.Threading.Thread.Sleep(3000); //mimic a lengthy process

            if(JobIsAlive != null ) //null means nobody subscribed to this

            {

                JobIsAlive(this, null);  //send event to say that job is still active

            }



            //Continue with more job



        }

    }

As you can see the member JobIsAlive is special. Its of a type event. EventHandler is the type of delegate this event expects. A delegate is basically a reference to a method. You can access a variable with its reference. Same way a method can be invoked/called via its reference. Lets write a simple forms project to consume it.

 public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private DoSomeWork d = new DoSomeWork();

        private void Form1_Load(object sender, EventArgs e)

        {

            

            d.JobIsAlive += d_JobIsAlive;

        }



        void d_JobIsAlive(object sender, EventArgs e)

        {

            MessageBox.Show("Job is active");

        }



        private void Start_Click(object sender, EventArgs e)

        {

            d.DoSomeVeryLargeWork();

        }



    }

We declared DoSomeWork as private member of Form1 class. On the form load method, we just subscribe to JobIsAlive event. When Start button is clicked the job starts. After 3 seconds an event get fired to indicate that the job is still active. So in a nutshell, you passed the consumer (DoSomeWork class) the reference of your method d_JobIsAlive and consumer invoked it to let you know that its active and kicking.

Create a solution. Add a C# library project to copy the DoSomeWork class to it. Add a form project to the solution and copy above code to the forms project and try it out.

Another great example to understand Events is FileSystem events. Suppose you want to monitor a folder on your computer for files being created there. Your vendor might copy business files to that folder or something of that sort. You may want to read that file and do some processing. One way is to continuously poll that folder for new files, which is not very efficient. The Windows file system raises a file created event every time a file is created on the disk( And a bunch of other events too). All that you need to do is subscribe to the created event of file system and do whatever you need to do.

Create an instance of FileSystemWatcher and set the path property to the path on your drive you want to monitor. Subscribe to the "Created" event of FileSystemWatcher to get notification each time a file is created on that particular folder. Attached is a simple WinForm project which will monitor C:\Temp folder for any file activity

public partial class FileWatch : Form
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        public FileWatch()
        {
            InitializeComponent();
        }

        private void FileWatch_Load(object sender, EventArgs e)
        {
            watcher = new FileSystemWatcher();
            watcher.Path = @"C:\temp";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;
            watcher.EnableRaisingEvents = true;
            watcher.Filter = "*.*";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed); 
        }
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
        }

        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            MessageBox.Show(String.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath));
        }
    }

We offer one on one C# training,SQL training,WCF training,WPF training,WinForms training, MVC training, ASP.NET training, Ajax & Javascript training. Please see the contacts page