在这个C#示例中,如何避免while(true)

在这个C#示例中,如何避免while(true),c#,multithreading,events,monitor,C#,Multithreading,Events,Monitor,我正在寻找一种方法,以更有效的方式(例如,事件驱动代码)来取代这个while循环 While(true)\\ must constantly monitor units { if(units.count< 10) { \\ launch units } thread.sleep(100); \\ to avoid 100% CPU usage } While(true)\\必须持续监控装置 { 如果(单位计数

我正在寻找一种方法,以更有效的方式(例如,事件驱动代码)来取代这个while循环

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

  thread.sleep(100); \\ to avoid 100% CPU usage
}
While(true)\\必须持续监控装置
{ 
如果(单位计数<10)
{    
\\发射装置
}
thread.sleep(100);\\n避免100%的CPU使用率
}
可以在其他线程中删除单元,它们位于线程安全的concurrentDictionary中

我将非常感谢您对更好地实施此代码的建议


谢谢

您可以使用计时器清除
while
线程。睡眠
同时清除主线程上的阻塞:

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;
}
time-devent上的私有静态void(对象源,System.Timers.ElapsedEventArgs e)
{
如果(单位成本<10)
{    
//发射装置
}
}
公共静态void Main(字符串[]args)
{
System.Timers.Timer aTimer=新的System.Timers.Timer();
aTimer.Appead+=新系统.Timers.ElapsedEventHandler(OnTimedEvent);
a时间间隔=100;
aTimer.Enabled=true;
}
工作示例:


下面是我使用事件创建的一个示例,它显然不完整,但您应该能够向它添加所需内容,以获得您想要的方式

当从字典中删除键时,它检查字典的计数,如果计数小于指定的数字,则触发事件

注意:我不知道这是否是线程安全的,我不熟悉使用线程,我希望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;
        }
    }
}
公共静态部分类程序
{
静态void Main(字符串[]参数)
{
DictionaryCount dict=新DictionaryCount();
dict.CountLessThan+=dict_TryRemove;
dict.CountToFireOn=1;
dict.TryAdd(1,“你好”);
dict.TryAdd(2,“世界”);
dict.TryAdd(3,“!”);
字符串输出值;
dict.TryRemove(2,out out value);
dict.TryRemove(1,out out value);
Console.ReadKey(true);
}
私有静态void dict_TryRemove(对象发送方,CountEventArgs e)
{
DictionaryCount dict=发送方作为DictionaryCount;
控制台写入线(dict.Count);
Console.WriteLine(“计数小于2!”);
}
公共类字典计数:ConcurrentDictionary
{
public int CountToFireOn{get;set;}
公共字典计数():基(){}
公共委托void CountEventHandler(对象发送方,CountEventArgs e);
公共事件CountEventHandler CountLessThan;
public new bool TryRemove(TKey键,out TValue值)
{
bool retVal=base.TryRemove(键,输出值);

如果(this.Count)希望它始终运行,While有什么问题(true)?否则,如果您打开一个控制台,您可以在按下按钮时将其关闭。这样会消耗大量CPU时间。我正在寻找一种方法,每当units.count以某种方式降至10以下时运行此部件!您必须检查它是否低于10,并且这会占用CPU。可能检查的频率较低?您可以创建一个触发的事件或只是只要调用一个方法,在任何代码位更新
单位时执行检查。如果您控制所有可以更改
单位的代码,那么您就不需要像现在这样轮询更改。您可以通过事件方式、计时器方式、计划方式、取消等待方式、异步方式等方式来执行此操作。范围太广,无法实现回答,伊姆霍