CPU使用率を監視し続けるスレッドがWindowsサービスに必要です(たぶん5秒ごと)。 CPU使用率が低い場合は、他のスレッドをアクティブにする必要があります。CPU使用率のスレッドを継続的に監視する
私はこのSO QuestionからのサンプルCPU使用率監視コードを見つけました。これはコンソールアプリケーションのコードで、Timer
を生きたままにしておくと、人は最後にConsole.ReadLine();
を使用しています。
CPU使用率コンソールアプリケーション:
using System;
using System.Diagnostics;
using System.Timers;
using System.Threading;
using System.Collections.Generic;
namespace CPUPerformanceMonitor
{
class MonitoringApplication
{
protected static PerformanceCounter cpuCounter;
protected static PerformanceCounter ramCounter;
public static void TimerElapsed(object source, ElapsedEventArgs e)
{
float cpu = cpuCounter.NextValue();
float ram = ramCounter.NextValue();
Console.WriteLine(string.Format("CPU Value: {0}, ram value: {1}", cpu, ram));
}
public static void Main()
{
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
try
{
System.Timers.Timer t = new System.Timers.Timer(1200);
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
Thread.Sleep(10000);
}
catch (Exception e)
{
Console.WriteLine("catched exception");
}
while (true) //Another sample BAD way to keep the timer alive
{ }
//Console.ReadLine(); //just to keep the time alive
}
}
}
問題:どのように私は、Windowsサービスアプリケーションでそれを実装します。つまり、どうやってスレッドを生かし続けるのか。
私のWindowsサービスの構造:
私はスレッドのコールバックメソッドOnStart()
を呼び出します。このスレッドコールバックメソッドは、CPUMonitor
(Timer
のコードを含む)のStartCPUMonitorinig()
メソッドを呼び出します。あなたはどこで、どのように出力パフォーマンスデータにしたいですか検討する必要がありService
タイプにこれを実装するに
public void CPUMonitorinigThreadCallback()
{
//If nothing is there in this function, the thread will start up and then immediately shutdown. To deal with this situation, use "_shutdownEvent"
//The while loop checks the ManualResetEvent to see if it is "set" or not.
while (!_shutdownEvent.WaitOne(0))
{
// Replace the Sleep() call with the work you need to do
//Sleep(1000);
objCPUMonitor.StartCPUMonitorinig();
}
}
あなたはこれが間違った方法に近づいていると思います。基本的には、CPU使用率が低い場合に限り、いくつかの作業を完了しようとしているようです。ワーカースレッド(バックグラウンド、アイドルなど)の優先度を単純に下げることができると考えましたか?私があなたの意図を誤解した場合、あなたが達成しようとしているもの(一般的には)の広範なイメージを私に与えることができますか? –
なぜスレッドが必要ですか?タイマーを使って5秒ごとに発砲することができます。 – CodeWeed
Windowsサービススレッドはスリープ状態にはなりません。あなたは基本的に何もする必要はありません、それは生き続けるでしょう、あなたがイベントに登録する限り、彼らは育てられます\ – zaitsman