增加/减少SemaphoreSlim中可用插槽的数量

时间:2016-03-28 22:38:06

标签: c# .net multithreading

编辑我的问题,正如最初的措辞,暗示SemaphoreSlim创建并销毁不准确的线程。重新措辞使用"插槽"而不是"线程",我相信这更准确。

我使用SemaphoreSlim类来控制我访问给定资源的速率,它运行良好。但是,我很难动态地增加和减少可用的插槽数量。

理想情况下,SemaphoreSlim具有Increase()Decrease()方法,具有以下特征:

  • Increase()会将可用的最大插槽数增加1
  • Decrease()将可用的最大插槽数减少1
  • 这些方法不等待,立即返回
  • 当达到可配置的最大插槽数时,后续对Increase()的调用等同于noop(不会抛出异常)
  • 当达到可配置的最小插槽数时,后续对Decrease()的调用等同于noop(不会抛出异常)
  • 当调用Decrease()并且所有插槽都在使用时,释放插槽时最大插槽数会减少

是否有允许这样的.NET构造?

2 个答案:

答案 0 :(得分:0)

正如评论中已经提到的,信号量既不会创建也不会破坏线程。您正在描述和可能正在搜索的是ThreadPool类的功能。它有一些方法,如SetMinThreadsSetMaxThreadsQueueUserWorkItem,并且非常肯定会完全符合您的要求。

答案 1 :(得分:0)

我建议使用以下扩展方法来增加插槽数量(最多可达到配置的最大值):

public static void Increase(this SemaphoreSlim semaphore)
{
  try
  {
    semaphore.Release();
  }
  catch
  {
    // An exception is thrown if we attempt to exceed the max number of concurrent tasks
    // It's safe to ignore this exception
  }
}

这种扩展方法可以这样使用:

var semaphore = new SemaphoreSlim(2, 5);  // two slot are initially available and the max is 5 slots
semaphore.Increase();  // three slots are now available
semaphore.Increase();  // four slots are now available
semaphore.Increase();  // five slots are now available
semaphore.Increase();  // we are attempting to exceed the max; an exception is thrown but it's caught and ignored. The number of available slots remains five

现在我需要弄清楚如何实现"降低()"方法。有什么建议吗?