gpt4 book ai didi

c# - 更少锁定的线程安全

转载 作者:行者123 更新时间:2023-11-30 18:37:24 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
C# Threading & Blocking

我正在尝试有效地确定哪种方法更好:

目前,我有一个单例实例,它公开以延迟加载方式加载的实体。我列出了三种方法,每种方法都有一些优点。第一种方法完全依赖双锁模式来确保线程安全。第二种方法不使用锁定,但它有可能在比赛中使用双倍负载。第三种方法确实使用了一种我越来越喜欢的解决方案。 (System.Lazy)。

出于某种原因,我觉得第二种方法 (System.Thread.InterLocked) 有问题,但我无法指出它。是否有理由支持一种方法而不是另一种方法?我在上一篇文章中确实介绍了这一点,我觉得第三种选择是从现在开始的方式。

我将代码剥离到准系统,以便能够解释设计。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TPLDemo
{
public class SomeEntity
{
}

public class MultiThreadedManager
{
private static readonly System.Lazy<MultiThreadedManager> instance = new Lazy<MultiThreadedManager>(() => { return new MultiThreadedManager(); });
private readonly object _syncRoot = new object();
private List<SomeEntity> _inMemoryEntities = null;
private List<SomeEntity> _inMemoryEntitiesUsingLockFreeApproach = null;
private System.Lazy<List<SomeEntity>> _inMemoryUsingLazy = new Lazy<List<SomeEntity>>(() => { return MultiThreadedManager.Instance.LoadFromSomewhere(); });

public static MultiThreadedManager Instance
{
get { return instance.Value; }
}


public IEnumerable<SomeEntity> LazyEntities
{
get
{
return _inMemoryUsingLazy.Value;
}
}

public IEnumerable<SomeEntity> LocklessEntities
{
get
{
if (_inMemoryEntitiesUsingLockFreeApproach == null)
{
do
{
// Is it possible multiple threads hit this at the same time?
} while (System.Threading.Interlocked.CompareExchange<List<SomeEntity>>(ref _inMemoryEntitiesUsingLockFreeApproach, this.LoadFromSomewhere(), null) != null);
}

return _inMemoryEntitiesUsingLockFreeApproach;
}
}


/// <summary>
/// This is thread safe but it involved some locking.
/// </summary>
public IEnumerable<SomeEntity> Entities
{
get
{
if (_inMemoryEntities == null)
{
lock (_syncRoot)
{
if (_inMemoryEntities == null)
{
List<SomeEntity> list = this.LoadFromSomewhere();
_inMemoryEntities = list;
}
}
}

return _inMemoryEntities;
}
}

private List<SomeEntity> LoadFromSomewhere()
{
return new List<SomeEntity>();
}

public void ReloadEntities()
{
// This is sufficient becasue any subsequent call will reload them safely.
_inMemoryEntities = null;

// This is sufficient becasue any subsequent call will reload them safely.
_inMemoryEntitiesUsingLockFreeApproach = null;

// This is necessary becasue _inMemoryUsingLazy.Value is readonly.
_inMemoryUsingLazy = new Lazy<List<SomeEntity>>(() => { return MultiThreadedManager.Instance.LoadFromSomewhere(); });
}
}
}

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