以下是我使用事件創建的示例,它顯然不完整,但您應該能夠添加所需內容以獲得它所需的方式。
它檢查字典的計數,當一個鍵被刪除時,然後在計數小於指定的數字時觸發該事件。
注意:我不知道這是否是線程安全的,我不熟悉使用線程,希望ConcurrentDictionary正在處理這個問題。
public static partial class Program
{
static void Main(string[] args)
{
DictionaryCount<int, string> dict = new DictionaryCount<int, string>();
dict.CountLessThan += dict_TryRemove;
dict.CountToFireOn = 1;
dict.TryAdd(1, "hello");
dict.TryAdd(2, "world");
dict.TryAdd(3, "!");
string outValue;
dict.TryRemove(2, out outValue);
dict.TryRemove(1, out outValue);
Console.ReadKey(true);
}
private static void dict_TryRemove(object sender, CountEventArgs e)
{
DictionaryCount<int, string> dict = sender as DictionaryCount<int, string>;
Console.WriteLine(dict.Count);
Console.WriteLine("Count less than 2!");
}
public class DictionaryCount<TKey, TValue> : ConcurrentDictionary<TKey, TValue>
{
public int CountToFireOn { get; set; }
public DictionaryCount() : base() { }
public delegate void CountEventHandler(object sender, CountEventArgs e);
public event CountEventHandler CountLessThan;
public new bool TryRemove(TKey key, out TValue value)
{
bool retVal = base.TryRemove(key, out value);
if (this.Count <= CountToFireOn)
{
CountEventArgs args = new CountEventArgs(this.Count);
CountLessThan(this, args);
}
return retVal;
}
}
public class CountEventArgs
{
public int Count { get; set; }
public CountEventArgs(int count)
{
this.Count = count;
}
}
}
如果你想讓它始終運行,While(true)有什麼問題?否則,如果您打開一個控制檯,則可以在按下按鈕時將其關閉。 – coinbird
以這種方式消耗大量CPU時間。我正在尋找一種方式來運行這個piecely每當units.count降到10以下! –
你必須檢查它是否低於10,並使用CPU。也許檢查的次數不多? – coinbird