3

In a thread resolved yesterday, @hvd showed me how to get "control" over exception handling by .Invoke when dealing with delegates of unknown type (an issue seen in libraries like Isis2, where the end-user provides polymorphic event handlers and the library type-matches to decide which to call). Hvd's suggestion revolved around knowing how many arguments the upcall handler received and then using that information to construct a generic of the right type, which allowed him to construct a dynamic object and invoke it. The sequence yielded full control over exception handling.

The core of his suggestion was that Isis2 might consider doing upcalls this way:

MethodInfo mi = typeof(Program).GetMethod("Foo", BindingFlags.Static | BindingFlags.NonPublic); 
Delegate del = Delegate.CreateDelegate(typeof(Action<,>).MakeGenericType(mi.GetParameters().Select(p => p.ParameterType).ToArray()), mi);
((dynamic)del).Invoke(arg0, arg1);

Here's my question: Can anyone suggest a way to do this same thing that works for an arbitrary number of arguments? Clearly I can do a switch statement and write code for the case of 1 arg, 2, etc. But is there a way to do it where mi.GetParameters().Length tells us how many arguments?

As a capsule summary for those who don't want to click the link, the core issue is this: when doing these kinds of dynamic upcalls, the end-user (who registered the method being called) may throw an exception due to bugs. Turns out that when not running under Visual Studio -- when running directly in the CLR -- the C# .Invoke will catch and rethrow exceptions, packaging them as inner exceptions inside a InvocationTargetException. This unwinds the stack and causes the user to perceive the bug as having been some kind of problem with the code that called .Invoke (e.g. with MY code). This is why the C# reference manual argues that catch/rethrow is poor coding practice: one should only catch exceptions that one plans to handle...

hvd explained that this was basically because .Invoke had no clue as to the number or types of the arguments and in that mode, apparently, catchs and rethrows exceptions for some reason. His workaround essentially pins down the number of arguments (the generic in the example: Action<,>) and this apparently is enough so that .Invoke doesn't do a "universal catch". But to use his example for arbitrary code, I need a case for each possible number of parameters. Doable (after all, who would ever want more than 16?) but ugly!

Hence today's challenge: Improve that code so that with a similar 3 line snippet of C# it works no matter how many parameters. Of course the resulting delegate needs to be callable too, presumably with a vector of objects, one per argument...

PS: One reason for pessimism: Action itself comes in 16 forms, with 1 to 16 arguments. So to me this suggests that the C# developers didn't see a more general way to do it, and ended up with the version that would correspond to me using a switch statement (and I guess the switch would have cases for 0 to 16 arguments, since I would need an Action<...> with N type arguments to handle N user-supplied arguments!)

Community
  • 1
  • 1
Ken Birman
  • 1,088
  • 8
  • 25
  • 1
    Why do you try so hard to avoid the behavior of `DynamicInvoke()`? Catching and rethrowing exception is a normal practice in .Net. When investigating exceptions, you should always look at the `InnerException` and I would expect the users of your library to do exactly that. Why is it such a huge problem for you? – svick Mar 18 '12 at 15:20
  • @svick, the problem is that if the end-user who provided the event handler has complex logic, and that code throws an exception, catching and rethrowing the exception unwinds the stack and we lose much of the context needed to debug the problem -- sure, we know which line the null reference happened on (because this is part of the inner exception) but we won't know what variables had what values, what the arguments were to the methods on the call stack (we do know who called what, and from what line, but nothing more), etc. So a lot of useful data is lost when a catch/rethrow occurs – Ken Birman Mar 18 '12 at 15:29
  • What's wrong with `typeof(Program).GetMethod("Foo", BindingFlags.Static | BindingFlags.NonPublic, null, args.Select(x => x.GetType()).ToArray(), null).Invoke(null, args);`? – Tim S. Mar 18 '12 at 15:30
  • That's the version that would end up catching and rethrowing exceptions, hence unwinding the stack. I have a code example you can run on the other thread mentioned above. If VS is attached the exception will be caught on the right line, but if run directly in the CLR (e.g. double click the .exe), you get this rethrown exception and VS will show you the line that did the Invoke, not the code that threw the inner exception. [PS: I have no idea WHY .Invoke has that behavior when called this way, simply that it does so.] – Ken Birman Mar 18 '12 at 15:33
  • But that happens only in the very specific case when you don't start with a debugger and only attach it later. If you start with a debugger and have first chance exception catching turned on, you don't have that problem. – svick Mar 18 '12 at 15:33
  • My environment (cloud computing) is one where people would routinely launch 25 or 50 instances. You can attach VS to the full set but then VS sees too many threads and switches to a very annoying mode that limits functionality and won't show stack traces very easily. If you wait until the exception has been thrown, though, this catch/rethrow has already occured. – Ken Birman Mar 18 '12 at 15:38

1 Answers1

0

I don't want to leave this open forever, so I've done what I could to understand the core issue, including downloading the code for .Invoke in Mono. As far as I can tell, the original problem is simply due to an optimization that favors faster invocations at the cost of catching exceptions this way when a dynamic Invoke is done on an object with an argument vector. The code for a dynamic delegate created using the generic template simply doesn't have this catch in it.

Not a great answer but without access to the .NET implementation of Invoke, it apparently won't be possible to give a better one.

Ken Birman
  • 1,088
  • 8
  • 25