Jacob Jacob - 1 year ago 132
C# Question

InvalidOperationException in my Lazy<> value factory

I have a class containing something like the following:

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

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

In accessing the
property, I encountered this

ValueFactory attempted to access the Value property of this instance.

I don't see anything in my "value factory" method that accesses the
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 Source

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<>.