简体   繁体   English

无法捕获延迟初始化期间引发的异常(C# .NET)

[英]Can't catch exception thrown during lazy initialization (C# .NET)

I am trying to initialize an expensive object, through .NET's Lazy class, that can fail due to an exception.我正在尝试通过 .NET 的 Lazy class 初始化昂贵的 object,这可能由于异常而失败。 The instance of the lazy class is cached because it is possible that on a subsequent attempt initialization can succeed.惰性 class 的实例被缓存,因为在后续尝试初始化时可能会成功。 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.根据 .NET 的PublicationOnly文档,该异常不会被缓存,因此可以尝试重新初始化该值。 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?现在编写我自己的懒惰 class 相当简单,但我想知道我是否错误地使用了 .NET 的懒惰 class 还是他们的错误?

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?如果您说它抛出异常但没有捕获它,那么......您是否在 Visual Studio 中运行,并在“调试”>“异常”菜单中检查了 ArgumentException 以告诉它总是在那里中断?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM