2016-10-25 93 views
0

我基本上有一個進程,它執行主要任務之前調用另一個可執行文件(需要大約半小時運行)。爲了讓客戶不會覺得程序掛起,併爲了調試的目的,我已經包含了一個單獨的線程,應該每隔500ms更新一次這個單獨進程的內存計數器。內存計數器線程不工作

出於某種原因,儘管可執行文件的內存使用量在運行期間始終保持一致(從100MiB到500MiB),但似乎並未更新。

我已經檢查過,循環肯定正在運行,我只是無法得到內存計數器更新(我無法檢查手錶,因爲我沒有必要的.exe在這臺機器上,在目標機器上安裝VS)。

這裏是代碼的有關章節,任何援助將不勝感激:

public static void Main() 
    { 

     try 
     { 
      Console.WindowWidth = 100; 
     } 
     catch 
     { 
      // ignored 
     } 
     ProcessStartInfo generateReport = new ProcessStartInfo 
     { 
      Arguments = 
       "/H /EH ReliabilityMontroseLOS /T D:\\InformerReports\\Archive\\ReliabilityData\\ICSSReport.csv", 
      CreateNoWindow = true, 
      FileName = @"C:\Invensys\Aim\AimInform\Inform.exe", 
      UseShellExecute = true 
     }; 
     Thread thread = new Thread(() => StartReportThread(generateReport)); 
     thread.Start(); 
     int x = 35; 
     int direction = 1; 
     Console.ForegroundColor = ConsoleColor.Green; 
     while (thread.IsAlive) 
     { 
      string line = ""; 
      for (int j = 0; j < x; j++) 
      { 
       line += " "; 
      } 
      line += "Collecting Data"; 
      string line2 = string.Format("AIM*Inform Memory Usage: {0} MiB", workingSet/Math.Pow(1024,2)); 
      Console.Clear(); 
      Console.WriteLine(line);   
      Console.WriteLine(line2);  
      x += direction; 
      if ((x == 80) || (x == 0)) 
      { 
       direction = -direction; 
      } 
      Thread.Sleep(500); 
     } 
//Everything else 

 private static void StartReportThread(ProcessStartInfo generateReport) 
    { 
     Process proc = Process.Start(generateReport); 
     while ((proc != null) && !proc.HasExited) 
     { 
      workingSet = proc.WorkingSet64; 
      Thread.Sleep(100); 
     } 
    } 

回答

1

原來的解決方案是非常簡單的。 System.Process嚴重高速緩存其所有字段,因此我需要手動觸發更新。底部的代碼現在讀取:

private static void StartReportThread(ProcessStartInfo generateReport) 
    { 
     Process proc = Process.Start(generateReport); 
     while ((proc != null) && !proc.HasExited) 
     { 
      proc.Refresh(); 
      workingSet = proc.WorkingSet64; 
      Thread.Sleep(50); 
     } 
    } 

這是完美的!