andrew4582

PerformanceStopWatch

Mar 17th, 2012
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Core.Threading {
  4.  
  5.     /// <summary>
  6.     /// Used to capture duration for Diagnostics
  7.     /// <example>
  8.     /*
  9.     //Example 1:
  10.     {
  11.         PerformanceStopWatch sw = new PerformanceStopWatch();
  12.  
  13.         sw.StopAction = (duration) => {
  14.             Debug.WriteLine("Time: " + duration);
  15.         };
  16.  
  17.         //... do work
  18.  
  19.         sw.Stop();
  20.     }
  21.     // Example 2:
  22.     {
  23.         PerformanceStopWatch sw = PerformanceStopWatch.Start((duration)=>{
  24.             Debug.WriteLine("Time: " + duration);
  25.         });
  26.  
  27.         //... do work
  28.  
  29.         sw.Stop();
  30.  
  31.     }
  32.         // Example 3:
  33.     {
  34.         using(PerformanceStopWatch sw = PerformanceStopWatch.Start((duration) => {
  35.             Debug.WriteLine("Time: " + duration);
  36.         })) {
  37.                    
  38.             //... do work
  39.                    
  40.         }//stop is called when PerformanceStopWatch->Dispose() is called
  41.  
  42.     }
  43.      */
  44.     /// </example>
  45.     /// </summary>
  46.     public class PerformanceStopWatch:IDisposable {
  47.  
  48.         public static PerformanceStopWatch Start(Action<TimeSpan> stopaction = null) {
  49.             return new PerformanceStopWatch(stopaction);
  50.         }
  51.  
  52.         readonly DateTime _started;
  53.         Action<TimeSpan> _stopaction;
  54.         TimeSpan _duration = TimeSpan.Zero;
  55.  
  56.         public PerformanceStopWatch(Action<TimeSpan> stopaction = null) {
  57.             _stopaction = stopaction;
  58.             _started = DateTime.Now;
  59.         }
  60.  
  61.         public Action<TimeSpan> StopAction {
  62.             get {
  63.                 return _stopaction;
  64.             }
  65.             set {
  66.                 _stopaction = value;
  67.             }
  68.         }
  69.  
  70.         public TimeSpan Duration {
  71.             get {
  72.  
  73.                 return _duration;
  74.             }
  75.         }
  76.  
  77.         public TimeSpan Stop() {
  78.             _duration = DateTime.Now.Subtract(_started);
  79.             if(_stopaction != null)
  80.                 _stopaction(_duration);
  81.             return _duration;
  82.         }
  83.  
  84.         public void Dispose() {
  85.             Stop();
  86.         }
  87.          
  88.     }    
  89. }
Add Comment
Please, Sign In to add comment