SemaphoreSlim(1)我怎么知道其他线程是否在等待

时间:2013-12-25 15:22:04

标签: c# multithreading synchronization semaphore

为了同步,我创建了一个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();

感谢。

1 个答案:

答案 0 :(得分:4)

对于快速和肮脏的东西,如何只保留一个包含计数的静态变量?

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();
}