I am trying to initialize an expensive object through the .NET Lazy class, which may fail due to an exception. An instance of a lazy class is cached because it is possible that on subsequent attempts, initialization may be successful. Therefore, I create an instance as follows:
Lazy<someObject> lazyValue = new Lazy<someObject>(() => { expensive initialization; }, System.Threading.LazyThreadSafetyMode.PublicationOnly);
According to .NET documentation with PublicationOnly, the exception will not be cached, and therefore, you can try to reinitialize the value. I ran into the problem that the exception cannot be caught. Now itβs quite simple to write your own lazy class, but I would like to know if I am using the .NET Lazy class incorrectly or their error?
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); } } }
Rehan
source share