Tuesday, 20 August 2013

The most simple c# event ever!

How to simply raise a basic event and subscribe to it really caused confusion for me. Even the most simplest of examples didn't seem all that easy to understand. Even now I don't pretend to understand them, but in my own limited way I can use them. 

For a long time I misunderstood what an event was capable of, thinking you could simply subscribe to a random event anywhere in your code and it would magically work. Of course I realise this is not the case. 

So, to my simplest of events:

I wish to raise an event once something has completed a task, normally once a background thread has finished processing. 

First I set-up the event and delegate which will be used for subscription and raising the event in the Class which is performing my work. 


public delegate void GetUsersWorkerIsComplete(object sender, EventArgs e, string myString);
public event GetUsersWorkerIsComplete UsersReturned;

Then I call the event, checking first that there is a subscriber to the event. 


if(UsersReturned != null)
  { 
     UsersReturned(this, EventArgs.Empty, returnlistOfUsers);
  }

Finally in the class which is calling the method under which this work is performed, I subscribe to the event and handle it. 


void GetUser()
 {
    var users = new Classes.Server.Users.GetLocalDetails();

    users.UsersReturned += Users_UsersReturned; //My event subscriber

    users.AllUsers(); //The method I'm calling which eventually calls the event.
}
//My Event Handler
void Users_UsersReturned(object sender, EventArgs e, string myString)
{
    string myEventString = myString;
}

No comments:

Post a Comment