2017-04-26 264 views
-3

我正在尋找一種方法,以更高效的事件替代此循環,例如事件驅動的代碼。如何避免while(true)在這個C#示例中

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

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

單位可以在其他線程中刪除,並且它們在線程安全的concurrentDictionary中。

我希望您能更好地實施此代碼的建議。

謝謝

+0

如果你想讓它始終運行,While(true)有什麼問題?否則,如果您打開一個控制檯,則可以在按下按鈕時將其關閉。 – coinbird

+0

以這種方式消耗大量CPU時間。我正在尋找一種方式來運行這個piecely每當units.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