.net 线程安全单例属性在一行中

0yg35tkg  于 2023-01-06  发布在  .NET
关注(0)|答案(2)|浏览(90)

我怎样才能在一行中写出下面的代码?

private static LockSDP instance;
        private static readonly object _lock = new();
        public static LockSDP GetInstance
        {
            get
            {
                if (instance is null) lock (_lock) instance ??= new();
                return instance;
            }
        }

fjnneemd

fjnneemd1#

不是所有的东西都可以是一条线;然而,这也许可以更容易些;您 * 可以 * 使用Lazy<T>,但对于这里的简单static(您主要是在延迟示例化之后),我可能会依赖于静态字段行为和嵌套类:

public static LockSDP GetInstance => LockProxy.Instance;
private static class LockProxy { public static readonly LockSDP Instance = new(); }
olmpazwi

olmpazwi2#

我可能更喜欢Marc's answer,但它就在那里:

private static readonly Lazy<LockSDP> _lazyInstance = 
    new Lazy<LockSDP>(() => new LockSDP()); // Default is Threadsafe access.

public static LockSDP Instance => _lazyInstance.Value;

是的:我确实意识到它仍然是2行:/
供参考:Lazy<T>

相关问题