2017-04-26 4 views
-3

이 while 루프를 이벤트 구동 코드와 같은보다 효율적인 것으로 대체하는 방법을 찾고 있습니다.이 C# 예에서 while (true)를 피하는 방법

While(true)\\ must constantly monitor units 
{ 
    if(units.count< 10) 
    {  
    \\ launch units  
    } 

    thread.sleep(100); \\ to avoid 100% CPU usage 
} 

단위는 다른 스레드에서 삭제할 수 있으며 thread safe 인 concurrentDictionary에 있습니다.

이 코드를 더 잘 구현해 주시면 감사하겠습니다.

감사합니다

+0

항상 실행하려면, While (true)가 잘못 되었습니까? 그렇지 않으면 콘솔을 열었을 때 버튼을 눌렀을 때 콘솔을 닫을 수 있습니다. – coinbird

+0

이렇게하면 CPU 시간이 많이 소모됩니다. unit.count가 어떻게 든 10 이하가 될 때마다이 조각을 실행할 수있는 방법을 찾고 있습니다! –

+0

10 미만인지 확인해야하며 CPU를 사용합니다. 어쩌면 자주 확인하지 않겠습니까? – coinbird

답변

1

다음은 이벤트를 사용하여 만든 예제입니다. 분명히 완전하지는 않지만 필요한 방식을 추가하여 원하는 방식으로 추가 할 수 있어야합니다.

키가 제거 될 때 사전의 수를 확인한 다음 수가 지정된 수보다 작 으면 이벤트를 실행합니다.

참고 : 스레드 안전성에 대해서는 잘 모르겠지만 스레드로 작업하는 것에 익숙하지는 않습니다. 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; 
     } 
    } 
} 
1
또한 주 스레드에서 막힘 치우는 동안이 (가) whilethread.sleep 제거하는 타이머를 사용할 수 있습니다

:

private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e) 
{ 
    if(unitsCount < 10) 
    {  
     //launch Units 
    } 
} 

public static void Main (string[] args) 
{ 
    System.Timers.Timer aTimer = new System.Timers.Timer(); 
    aTimer.Elapsed+=new System.Timers.ElapsedEventHandler(OnTimedEvent); 

    aTimer.Interval=100; 
    aTimer.Enabled=true; 
} 

근무 예 : fiddle

Timer Documentation

Related Answer