Wednesday, March 15, 2006

 

Remoting event callbacks

I recently had need to add an event call back from a remote object. I got it working with help from several useful articles, but mainly this
on Code Project.
Some tweaks I made were putting all the remoting setup bits and pieces in config files, but the most important was that I changed the server code so that rather than just raising the event it iterates through the event invocation list and invokes each delegate. This is because I noticed that if a client disappears without removing its event call back from the list the server would fail whenever the event was raised. By iterating the invocation list you can catch the offending delegate and handle it more gracefully (i.e. so that the clients don't all error and removing the orphaned delegate from the invocation list)
e.g.

Delegate[] invocationList = MyEvent.GetInvocationList();

foreach(Delegate d in invocationList)
{
try
{
d.DynamicInvoke(new object[] {sessionId, trackNumber});
}
catch(System.Reflection.TargetInvocationException ex)
{
//the invocation failed.
//If the cause was that the service could not be found then
//remove the delegate from the invocation list
if (ex.InnerException.Message == "Requested Service not found")
{
MyEvent= (MyEventHandler)MyEventHandler.Remove(MyEvent, d);

//log the error
}
else
{
//otherwise rethrow the exception
throw(ex);
}
}
}

This page is powered by Blogger. Isn't yours?