Custom Event Handlers

Let’s say that you have a class that does some long running operation and you want your UI to be updated with the progress of the operation. You can resolve this nicely using custom event handlers.

Assume that the long running class is downloading files from somewhere and your UI needs to display the  file names as they are downloaded. The first step is to create event arguments to pass the file name information to your UI.

public class DownloadEventArgs : EventArgs
{
string fileName = null;
public string FileName
{
get
{
return fileName;
}
}

public DownloadEventArgs(string fileName)
{
this.fileName = fileName;
}
}

Next create an event handler delegate and an event in your long running class that uses the event arguments.

public delegate void DownloadEventHandler(object sender, DownloadEventArgs e);
public event DownloadEventHandler Download;

Next you need to raise the event in your class each time a file is downloaded.

Download(this, new DownloadEventArgs(downloadedfilename));

Now your class is fully prepared to report on each file after it is downloaded. Your UI can now subscribe to the events. Prepare an event handler that updates the status. Let’s say the UI is using WPF

void Downloader_Download(object sender, DownloadEventArgs e)
{
this.Dispatcher.Invoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate
{
lblStatus.Content = “Downloaded ” + e.FileName;
return null;
}), null);
}

Finally, you can subscribe to the events, so that the long running class calls your event handler.

downloader.Download += new Downloader.DownloadEventHandler(Downloader_Download);

The whole eventing system is in place. You start your downloader in a separate thread. Each time it downloads a file it raises the download event which calls your event handler in the UI. Even though it is running in a separate thread, the Dispatcher ensures that the status is updated in the correct thread context.

Advertisements
Tagged with:
Posted in Development

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: