views:

93

answers:

2

While I playing with the C# 4.0 dynamic, I found strange things happening with the code like this:

using System.Dynamic;

sealed class Foo : DynamicObject
{
    public override bool TryInvoke(
        InvokeBinder binder, object[] args, out object result)
    {
        result = new object();
        return true;
    }

    static void Main()
    {
        dynamic foo = new Foo();

        var t1 = foo(0);
        var t2 = foo(0);
        var t3 = foo(0);
        var t4 = foo(0);
        var t5 = foo(0);
    }
}

Ok, it works but... take a look at IntelliTrace window:

screenshot

So every invokation (and other operations too on dynamic object) causes throwing and catching strange exceptions twice!

I understand, that sometimes exceptions mechanism may be used for optimizations, for example first call to dynamic may be performed to some stub delegate, that simply throws exception - this may be like a signal to dynamic binder to resolve an correct member and re-point delegate. Next call to the same delegate will be performed without any checks.

But... behavior of the code above looks very strange. Maybe throwing and catching exceptions twice per any operation on DynamicObject - is a bug?

+2  A: 

I think the exceptions are caused by the debugger trying too inspect something.

If you tell Visual Studio to stop whenever a exception are thrown it does not stop and this indicates that the debugger is responsible for the exceptions not the actual code.

Arve
Seems you're right, Arve! I've launch PerformanceMonitor to check the Thrown exceptions count and run the program in release build without the debugger - no exceptions are throwing...
ControlFlow
Just enable first-chance exceptions in Debug -> Exceptions (Ctrl+D,E) and check all the check boxes. You will hit this.
Kirill Osenkov
+2  A: 

Thanks, I've opened a bug, we're looking at it. I'll update this once I hear from the Compiler team. It's throwing in the C# runtime binder (Microsoft.CSharp.dll).

If you enable first-chance exceptions in Debug.Exceptions, you will hit this. IntelliTrace has nothing to do with the bug, it's just showing you the first-chance exception being thrown and swallowed.

Kirill Osenkov
Thank you, Kirill! Don't know about first-chance exceptions...
ControlFlow
http://blogs.msdn.com/kirillosenkov/archive/2008/12/07/how-to-debug-crashes-and-hangs.aspx :)
Kirill Osenkov