c# .net core 使用配置实例化 SemaphoreSlim

c# .net core Instantiating SemaphoreSlim with configuration

当我实例化 SemaphoreSlim 时 class 我想为 initialCount 参数使用配置键,这样就好像值需要更改一样我们不需要进行完整的重建。

我目前的实施是有效的:

public class Handler
{
    private static SemaphoreSlim pool;
    private static readonly object lockObject = new();
    private static bool isInitialised;

    public Handler(IConfiguration configuration)
    {
        if(isInitialised) return;
        int poolSize = configuration.GetValue("PoolSize", 3);
        lock(lockObject)
        {
            pool ??= new SemaphoreSlim(poolSize);
            isInitialised = true;
        }
    }
}

我对这种方法感到有点不舒服,我不会说我非常有信心它是正确的解决方案。

有更好的方法吗?

您可以使用Lazy来简化您的初始化代码

static Lazy<SemaphoreSlim> pool = null;
public Handler(IConfiguration configuration)
{
    int poolSize = configuration.GetValue("PoolSize", 3);
    pool = new Lazy<SemaphoreSlim>(() => new SemaphoreSlim(10), LazyThreadSafetyMode.ExecutionAndPublication);
}

它的工作方式与您现有的代码类似,但我总是更喜欢在可用时使用框架方法进行与线程相关的工作,因为它们由比一般人更了解线程的工程师优化。