gpt4 book ai didi

c# - 如果以线程安全的方式不为空则返回属性

转载 作者:行者123 更新时间:2023-11-30 20:21:16 28 4
gpt4 key购买 nike

我的问题实际上是对 this 的扩展所以关于测试属性的问题在返回之前是空的。我有类似的情况:

public class MyClass
{
private readonly string _Name { get; set; }
private readonly IEnumerable<T> _Values { get; set; }
private IEnumerable<T> _MyProp { get; private set; }
public IEnumerable<T> MyProp
{
get
{
if(_MyProp == null)
{
this.SetProp();
}
return this._MyProp;
}
private set;
}

public MyClass(string Name, IEnumerable<T> Values)
{
this._Name = Name;
this._Values = Values;
}

private void SetProp()
{
// Business logic using Name and Values
this._MyProp = resultOfLogic;
}

}

链接的 SO 问题的公认答案提到这不是线程安全的方法。有人可以建议为什么它不是,以及是否有办法以线程安全的方式做到这一点?

最佳答案

如果另一个线程正在运行,则该线程可以在测试和调用您的线程上的 SetProp() 之间调用 SetProp()

我使用这样的代码,以使其更安全:

   // Dedicated object to lock for this property only
private object myPropSync = new object();
private T _myPropVal;
public IEnumerable<T> MyProp
{
get
{
// Check if property is null
if(_myPropVal== null)
{
// If null -> make sure you are the only one in the next section
lock (myPropSync) {
// Re-test, because another thread can
// set the property while waiting for the lock
if (_myPropVal== null) {
this.SetProp();
}
}
}
return this._myPropVal;
}
private set {
lock (_myPropSync) {
_myPropVal = value;
}
}
}

关于c# - 如果以线程安全的方式不为空则返回属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309972/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com