다음은 이벤트를 사용하여 만든 예제입니다. 분명히 완전하지는 않지만 필요한 방식을 추가하여 원하는 방식으로 추가 할 수 있어야합니다.
키가 제거 될 때 사전의 수를 확인한 다음 수가 지정된 수보다 작 으면 이벤트를 실행합니다.
참고 : 스레드 안전성에 대해서는 잘 모르겠지만 스레드로 작업하는 것에 익숙하지는 않습니다. 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 시간이 많이 소모됩니다. unit.count가 어떻게 든 10 이하가 될 때마다이 조각을 실행할 수있는 방법을 찾고 있습니다! –
10 미만인지 확인해야하며 CPU를 사용합니다. 어쩌면 자주 확인하지 않겠습니까? – coinbird