InvalidOperationException in my Lazy<> value factory

Jacob picture Jacob · Jun 10, 2011 · Viewed 25.1k times · Source

I have a class containing something like the following:

public static class Config
{
    private static Lazy<ConfigSource> _cfgSrc = new Lazy<ConfigSource>(
        () => { /* "ValueFactory" here... */ },
        true);

    public static ConfigSource ConfigSource
    {
        get { return _cfgSrc.Value; }
    }
}

In accessing the ConfigSource property, I encountered this InvalidOperationException:

ValueFactory attempted to access the Value property of this instance.

I don't see anything in my "value factory" method that accesses the Value property. Is there anything else that could be triggering this exception? This problem only happens intermittently, but once it does, it takes resetting IIS to clear up the Exception (which appears to be cached once it occurs).

Answer

Jacob picture Jacob · Jun 28, 2011

It turned out that this error only occurred when trying to inspect the Value property of the Lazy<> in the Visual Studio debugger. Doing so appeared to create a deadlock because the accessing of Value then seemed to hang the thread for a long time until the InvalidOperationException finally occurred. I could never intercept the original Exception, so I couldn't see the inner stacktrace.

I'm just chalking this up as a bug in Visual Studio or their implementation of Lazy<>.