为了进行同步,我创建了一个SemaphoreSlim(1)。
这意味着如果我在类中具有此信号量的单个实例作为锁:

private SemaphoreSlim _initializationSemaphore = new SemaphoreSlim(1);
private bool _isInitialized = false;

public void Initialize()
{
  await _initializationSemaphore.WaitAsync();
  if (_isInitialized)
  {
     _logger.Warn("SDK is already initialized");
  }
  //Do some logic only once and only ..
  _isInitialized=true;
  _initializationSemaphore.Release();
}

进入函数的第一个线程将继续运行代码,其他线程将无法进入函数,直到第一个线程释放了信号量。
我的问题是-我怎么知道当前有多少个线程卡在其中:
await _initializationSemaphore.WaitAsync();

谢谢。

最佳答案

对于快速而肮脏的事情,如何只保留一个保存计数的静态变量呢?

private SemaphoreSlim _initializationSemaphore = new SemaphoreSlim(1);
private bool _isInitialized = false;
private static int _waitingThreads = 0;

public void Initialize()
{
  try
  {
      Interlocked.Increment(ref _waitingThreads);
      await _initializationSemaphore.WaitAsync();
  }
  finally
  {
      Interlocked.Decrement(ref _waitingThreads);
  }
  if (_isInitialized)
  {
     _logger.Warn("SDK is already initialized");
  }
  //Do some logic only once and only ..
  _isInitialized=true;
  _initializationSemaphore.Release();
}

09-06 04:56