Advertisement
NPSF3000

Performance Monitor Mockup

Mar 30th, 2016
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace ConsoleApplication2
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             System.Diagnostics.Debug.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
  11.             var rnd = new Random();
  12.  
  13.             while (!Console.KeyAvailable)  //Simulation loop, in reality the using will usually wrap an entire method!
  14.             {
  15.                 using (Performance.Monitor<Program>(100, 300, "This is a test loop!"))
  16.                     Thread.Sleep(rnd.Next(500));
  17.             };
  18.         }
  19.     }
  20.  
  21.     public static class Performance
  22.     {
  23.         public static Monitor Monitor<T>(int warnMs, int errorMs, string description = null,
  24.             [System.Runtime.CompilerServices.CallerMemberNameAttribute] string methodName = "")
  25.         {
  26.             return new Monitor(typeof(T), methodName, description, warnMs, errorMs);
  27.         }
  28.     }
  29.  
  30.     public class Monitor : IDisposable
  31.     {
  32.         private readonly System.Diagnostics.Stopwatch _watch;
  33.  
  34.         Type _callerType;
  35.         private readonly string _methodName;
  36.  
  37.         string _description;
  38.         int _warnMs, _errorMs;
  39.         public Monitor(Type callerType, string methodName, string description, int warnMs, int errorMs)
  40.         {
  41.             _watch = System.Diagnostics.Stopwatch.StartNew();
  42.             _callerType = callerType;
  43.             _methodName = methodName;
  44.             _description = description;
  45.             _warnMs = warnMs;
  46.             _errorMs = errorMs;
  47.         }
  48.  
  49.         public void Dispose()
  50.         {
  51.             _watch.Stop();
  52.  
  53.             var prefix = _watch.ElapsedMilliseconds > _errorMs ? "ERROR: " :
  54.                          _watch.ElapsedMilliseconds > _warnMs ? "WARNING: " : "";
  55.  
  56.             if (!string.IsNullOrWhiteSpace(_description))
  57.                 _description = "\nDescription: " + _description;
  58.  
  59.             System.Diagnostics.Debug.WriteLine(prefix + _callerType.Name + "." + _methodName + ": " + _watch.Elapsed.TotalSeconds + " seconds." + _description);
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement