Need to cast System.Delegate to one of my own delegates dynamically. How do I do this?

0

0to60

More importantly, WHY do I wanna do this?

Well, I have events that I raise asynchronously like this:

foreach(eventhandler handler in eventname.getinvocationlist())
handler.begininvoke();

Now, I'd like to put a callback in there so I can call endinvoke and catch
any exceptions that get thrown in event handling code. Now, to call
endinvoke, you have to save the IAsynchResult returned by begininvoke, and
then you have to call endinvoke on the same delegate instance. As you can
see from my snippet above, doing this in a loop would entail collections of
IAsynchResults and delegate instances. I find that to be less than elegant,
so I have a class that I create that stores the delegate instance and the ar
and contains the callback. My code then looks like this:

foreach(eventhandler handler in eventname.getinvocationlist())
{
EndInvokerClass endInvoker = new EndInvokerClass(handler);
endInvoker.ar = handler.begininvoke(new
AsyncCallback(endInvoker.endinvoke);
}

where EndInvokerClass.endInvoke()

looks like this:

endInvoke()
{
try
{
handler.endinvoke(ar);
}
catch(exception ex)
{
//notify the client of the exception that they should have caught in
their event handler in the first place
}
}

I would like to use this class for many different event handler types, so I
have the handler declared as System.Delegate in my class. The problem is,
you can't call .EndInvoke() on System.Delegate. Apparently it only works on
some delegate that you define yourself.

So, either I cast the delegates dynamically or I have to include a property
for every expected event handler type. Do you feel me here?
 
M

Mattias Sjögren

So, either I cast the delegates dynamically or I have to include a property
for every expected event handler type. Do you feel me here?

You could perhaps do a late bound call to EndInvoke with Reflection.

FWIW, this should be a lot easier to do in the next .NET version
(codename Whidbey) with the generics support they're adding.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top