Cannot catch an exception that occurred during lazy initialization (C # .NET)

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); } } } 
+8
c #
source share
1 answer

Well, it looks like it should work. If you say that he throws an exception but not catching it, then ... by chance, do you work in Visual Studio and check the ArgumentException in the Debug> Exceptions menu so that he always talks about it?

+5
source share

All Articles