2016-03-28 83 views
4

編輯我的問題,正如原來的措辭,暗示SemaphoreSlim創建並銷燬不準確的線程。重新措詞使用「插槽」而不是「線程」,我相信這更準確。增加/減少SemaphoreSlim中可用插槽的數量

我使用SemaphoreSlim類來控制我訪問給定資源的速率,它很好用。但是,我正在努力如何動態增加和減少可用插槽的數量。

理想地,該SemaphoreSlim將具有Increase()Decrease()方法具有以下特徵:

  • Increase()由1
  • Decrease()增加可用時隙的最大數目由1
  • 減小availble的時隙的最大數目
  • 這些方法不會等待,它們立即返回
  • 當達到可配置的最大插槽數時,後續調用Increase()相當於空操作(不會拋出異常)
  • 當到達時隙的配置的分鐘數,之後Decrease()調用是等同於空操作(不會拋出異常)
  • Decrease()被調用並且所有時隙在使用時,釋放插槽時,插槽的最大數量會減少

是否有.NET構造允許類似這樣的事情?

+1

信號量不會創建或銷燬線程。他們支持帖子並等待。你的意思是運行時可配置的可以訪問單個資源的線程數限制嗎? –

+0

它被稱爲「線程池」。你不願意使用現有的產品,但你當然可以購買替代產品。在你的谷歌查詢中加入「聰明」或「替代」一詞。 –

+0

好的我認爲我沒有使用正確的詞彙。我並不是想暗示SemaphoreSlim保留了一定數量的線程(雖然我只是重讀了我的問題,而這正是我所說的)。我的意思是說SemaphoreSlim充當「關守」,並允許限制有多少進程訪問某個資源。我希望能夠增加/減少「門」的數量,或者他們被稱爲「插槽」(希望這是正確的術語)。 – desautelsj

回答

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 

現在我需要找出如何實施「減少()」方法。任何建議?