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.
Nice post, if only I knew what you were talking about!
ReplyDelete