【问题标题】:Synchronise access to singleton object initialisation同步访问单例对象初始化
【发布时间】:2018-02-08 19:54:12
【问题描述】:

我正在从 dotnet 核心 Web 应用程序访问 EventStore。所有线程共享一个连接。连接在第一次访问时打开,我需要确保只有一个线程打开连接。以前我会使用lock,但后来我不能await 方法打开连接。

我发现 following snippet 的代码看起来应该可以解决问题:

public class AsyncLock : IDisposable
{
    private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);

    public async Task<AsyncLock> LockAsync()
    {
        await _semaphoreSlim.WaitAsync().ConfigureAwait(false);
        return this;
    }

    public void Dispose()
    {
        _semaphoreSlim.Release();
    }
}

并在我的代码中使用它:

private static readonly AsyncLock _mutex = new AsyncLock();
private volatile bool _isConnected = false;
private async Task EstablishConnected()
{
    if (!_isConnected)
    {
        using (await _mutex.LockAsync())
        {
            if (!_isConnected)
            {
                await _connection.ConnectAsync().ConfigureAwait(false);
                _isConnected = true;
            }
        }
    }
}

这是同步访问以初始化/打开与 EventStore 的连接的合理方法吗?

【问题讨论】:

标签: c# .net multithreading .net-core eventstoredb


【解决方案1】:

原来有一个有用的nuget library 和来自Stephen Cleary 的关联Github repo 是上面AsyncLock 类的替代品。

【讨论】:

    【解决方案2】:

    我认为你的方法是合理的。但是,如果您正在寻找管理初始化的异步方法,请查看 Microsoft.VisualStudio.Threading 包中的一些可用对象,例如 AsyncLazy。我不认为该软件包可用于 .NET 核心,但 source code 在 github 上并在 MIT 许可下。

    使用 AsyncLazy,您可以执行以下操作:

    public class MyEventStoreConsumer
    {
        private static readonly Func<Task<IEventStoreConnection>> getConnection;
    
        static MyEventStoreConsumer()
        {
            var eventStore = EventStoreConnection.Create(...);
            var connection = new AsyncLazy<IEventStoreConnection>(async () =>
            {
                await eventStore.ConnectAsync().ConfigureAwait(false);
                return eventStore;
            });
            getConnection = () => connection.GetValueAsync();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 2018-06-26
      • 2023-04-04
      • 1970-01-01
      • 2023-03-25
      • 2013-07-04
      • 2017-01-17
      • 1970-01-01
      相关资源
      最近更新 更多