I recently started using Lazy throughout my application, and I was wondering if there are any obvious negative aspects that I need to take into account when using Lazy<
Here's not quite a negative aspect, but a gotcha for lazy people :).
Lazy initializers are like static initializers. They get run once. If an exception is thrown, the exception is cached and subsequent calls to .Value would throw the same exception. This is by design and is mentioned in the docs ... http://msdn.microsoft.com/en-us/library/dd642329.aspx:
Exceptions that are thrown by valueFactory are cached.
Hence, code as below will never return a value:
bool firstTime = true;
Lazy lazyInt = new Lazy(() =>
{
if (firstTime)
{
firstTime = false;
throw new Exception("Always throws exception the very first time.");
}
return 21;
});
int? val = null;
while (val == null)
{
try
{
val = lazyInt.Value;
}
catch
{
}
}