I am trying to initialize an expensive object, through .NET's Lazy class, that can fail due to an exception. The instance of the lazy class is cached because it is possible that on a subsequent attempt initialization can succeed. I am thus creating the instance as follows:
Lazy<someObject> lazyValue =
new Lazy<someObject>(() => { expensive initialization; },
System.Threading.LazyThreadSafetyMode.PublicationOnly);
According to .NET's documentation with PublicationOnly the exception will not be cached and thus one can attempt to reinitialize the value. I ran into the issue that the exception cannot be caught. Now it is fairly simple to write my own lazy class but I would like to find out if I am using .NET's Lazy class incorrectly or is their a bug?
The following (simplified) code will reproduce the problem:
private static void DoesntWork()
{
int i = 0;
Lazy<string> lazyValue = new Lazy<string>(() =>
{
if (i < 2)
{
throw new Exception("catch me " + i);
}
return "Initialized";
}, System.Threading.LazyThreadSafetyMode.PublicationOnly);
for (; i < 3; i++)
{
try
{
Console.WriteLine(lazyValue.Value);
}
catch (Exception exc) // I do not catch the exception!
{
Console.WriteLine(exc.Message);
}
}
}
Well, it looks like it should work. If you're saying that it's throwing the exception but not catching it, then... by any chance, are you running in Visual Studio, and have ArgumentException checked in the Debug > Exceptions menu for telling it to always break there?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With