home links tools blog about

AngryPets Blog

home

Delegates Rool


Seriously. Delegates. They leave me without speech. They're by far one of my favorite things in .NET. You can use them to make things so much cleaner it's not even funny. I've been struggling for a few days with how to make a couple of complex interactions 'clean.' I've tried a number of approaches. All of the stunk. Then it hit me. A spiffy way to do it with a delegate.

I never would have thought of it had it not been for the fact that I'm coding a winforms app, and I like to do most of my operations on background threads - which require threadstart delegates. My thought was, if I was just going to start a thread anywho... wouldn't it be nice to DYNAMICALY assign where that thread would start?

I'm sure threading weenies have figured this out well before me. But this made me no end of happy.

Asumme the following enum, or something similar:

public enum OperationType
{
    Hard,
    ReallyHard,
    SuperHard,
    AreYouKiddingHard
}

Then assume that you've got a handful of radio buttons, one for each of the enum options above. Each time a radio button is selected, a private member variable 'records' the current OperationType. Then when a submit button is pushed:

private void operationPicker_Click(object sender, EventArgs e)
{
    OperationDelegate op = null;
    switch (OperationType)
    {
        case OperationType.Hard:
            op = new OperationDelegate(this.HardHandler);
            break;
        case OperationType.ReallyHard:
            op = new OperationDelegate(this.ReallyHardHandler);
            break;
        // etc... 
        default:
            break;
    }

    if (op != null)
    {
        Thread background = new Thread(new ThreadStart(op));
        background.IsBackground = true;
        background.Start();
    }
}

Of course, the OperationDelegate could just be a ThreadStartDelegate - i.e. void that returns a void (and that's the beauty of delegates - signatures are all that have to match), but I prefer to roll my own delegates (yeah, sounds tough.. but we all know the truth). Then, of course, whatever evil is in your specified operation will begin, etc. In my mind, that's some hard core pwnage.


posted on Saturday, September 10, 2005 9:47 PM
 

Existing Comments:

# Delegate Rool and VB.NET Drools - Posted: 9/12/2005 5:12 PM - By: AngryPets.com :: Blog
   



Add your own comment:


Go to http://blog.angrypets.com where comments are enabled.