2016-09-22 114 views
0

是否可以優化我的控制檯應用程序?由於while(true)循環,它使用多達60%的CPU。 這個想法是每次啓動時都會終止Microsoft管理控制檯(服務)進程。並啓動/停止服務 - 使用pswrd和控制檯。用while(true)循環監視進程

public static void Main(string[] args) 
    { 
     Thread consoleInput = new Thread(_consoleInput); 
     consoleInput.Start(); 
     killProcess(); 
    } 

static void _consoleInput(){ 
     getPassword(); 
     sendServiceCommands(); 
    } 
    static void killProcess(){ 
     while(true){ 
      try{ 
       System.Diagnostics.Process[] myProcs = System.Diagnostics.Process.GetProcessesByName("mmc"); 
       myProcs[0].Kill(); 
       } 
      catch(Exception e){} 
     }   
    } 

+1

通常情況下,越多優化越多。以50%的使用率迭代100k對象的程序可能比以100%的使用率迭代它們的程序要慢。如果你想每次使用較少的CPU,那麼你可以添加一個睡眠,while(true){doStuff(); System.Threading.Thread.Sleep(100); }'在迭代之間睡100ms。 – Quantic

回答

0

你需要System.Threading.Timer。類似這樣的:

public class Killer 
{ 
    protected const int timerInterval = 1000; // define here interval between ticks 

    protected Timer timer = new Timer(timerInterval); // creating timer 

    public Killer() 
    { 
     timer.Elapsed += Timer_Elapsed;  
    } 

    public void Start() 
    { 
     timer.Start(); 
    } 

    public void Stop() 
    { 
     timer.Stop(); 
    } 

    public void Timer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     try 
     { 
      System.Diagnostics.Process[] myProcs = System.Diagnostics.Process.GetProcessesByName("mmc"); 
      myProcs[0].Kill(); 
     } 
     catch {} 
    } 
} 

... 

public static void Main(string[] args) 
{ 
    Killer killer = new Killer(); 
    Thread consoleInput = new Thread(_consoleInput); 
    _consoleInput.Start(); 
    killer.Start(); 

    ... 

    // whenever you want you may stop your killer 
    killer.Stop(); 
}