8 Jul 2010

C# delegate reminder

I can't be the only person who forgets how to set up a multicast delegate handler EVERY SINGLE TIME I need one. I guess it just feels messy the way you have to declare the delegate, then create an instance of it, then hook up methods to it, then create an invocation method to call the InvocationList....

Anyway, here's a cheat sheet for a typical ASP.NET page or control implementing a multicast delegate, primarily for myself, but may help someone else, who knows....


public delegate void MyDelegateDef();
public MyDelegateDef MyDelegateInstance = null;
readonly object invocationLock = new object();

private void InvokeMyDelegateInstance()
{
MyDelegateDef handler;
lock (invocationLock) // Lock to get a thread-safe reference
{
handler = MyDelegateInstance;
}

if (handler != null)
{
foreach (MyDelegateDef delegateMethod in handler.GetInvocationList())
delegateMethod();
}
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

// Run methods that are hooked up to MyDelegateInstance by this point
InvokeMyDelegateInstance();
}


Then anything that needs to hook up to the delegate does it like so (assumes the delegate is declared in an object instance called myControlInstance):


private void onDelegateEvent()
{
// Do your stuff here
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);

// Registers onDelegateEvent() to be called when MyDelegateInstance is invoked
myControlInstance.MyDelegateInstance += onDelegateEvent;
}



Okay, so EventHandlers should probably be used in this ASP.NET scenario rather than pure delegates, but the principal is sound!

Incidentally, Jon Skeet is the master at this stuff and you should probably read this and then buy his book.

1 comment:

  1. Anonymous11:53 pm

    Nice post, if only I knew what you were talking about!

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!