。結果はパフォーマンスカウンターに送られます。
次のコントローラでは、PerformanceCountersが1回作成されてから再使用されます。タイマーは、最初の呼び出しが行われる前に500ミリ秒が経過したことを保証します。
public class PerformanceController : Controller
{
static PerformanceCounter ramCounter;
static PerformanceCounter cpuCounter;
static Timer timer;
static ManualResetEvent waiter = new ManualResetEvent(false);
static Performance lastMeasure = new Performance(); // the Model (in Mvc)
static PerformanceController()
{
// Get the current process
using (var p = Process.GetCurrentProcess())
{
ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
}
// make sure some time has passed before first NextValue call
timer = new Timer(s =>
{
waiter.Set();
}, null, 500, Timeout.Infinite);
// clean-up
AppDomain.CurrentDomain.DomainUnload += (s, e) => {
var time = (IDisposable)timer;
if (time != null) time.Dispose();
var wait = (IDisposable)waiter;
if (wait != null) wait.Dispose();
var rc = (IDisposable)ramCounter;
if (rc != null) rc.Dispose();
var cc = (IDisposable)cpuCounter;
if (cc != null) cc.Dispose();
};
}
private static Performance GetReading()
{
// wait for the first reading
waiter.WaitOne();
// maybe cache its values for a few seconds
lastMeasure.Cpu = cpuCounter.NextValue();
lastMeasure.Ram = ramCounter.NextValue();
return lastMeasure;
}
//
// GET: /Performance/
public ActionResult Index()
{
return View(GetReading());
}
}
パフォーマンスモデルは本当に簡単です:
public class Performance
{
public double Ram { get; set; }
public double Cpu { get; set; }
}
そして、次のビューが実装
@model MvcApplication1.Models.Performance
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div><span>Ram</span><span>@Model.Ram</span> </div>
<div><span>Cpu</span><span>@Model.Cpu</span> </div>
@CodeCasterを完了し、あなたの編集は本当にパフォーマンスを得る、質問の意図を変更しますコンソールアプリケーションはMVCアプリケーションのパフォーマンスを得ることとは非常に異なりますし、質問が書かれている方法では、OPがコンソールアプリケーション用に望んでいるように見えるようになりました。タグとタイトルが表示されます。 –
@Scott OPが自分自身を正しく表現できないのは私の問題ではない。タイトルに「MVC」と言って、「model-view-controller」タグを適用するのは、私の意見では、「このコンソールのアプリケーションコードをMVCに翻訳する」という意味ではありません。そうであれば、OPは自由にそのフレーズを質問に編集することができます。 – CodeCaster
@Scottと言われていますが、私は "asp.net-mvc"タグを適用しました。 (また、私の意見では、もし誰かが[この州の質問](http://stackoverflow.com/revisions/38046532/2)に答えようとするなら、それを編集して読みやすくするべきです)。 – CodeCaster