Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Core.Threading {
- /// <summary>
- /// Used to capture duration for Diagnostics
- /// <example>
- /*
- //Example 1:
- {
- PerformanceStopWatch sw = new PerformanceStopWatch();
- sw.StopAction = (duration) => {
- Debug.WriteLine("Time: " + duration);
- };
- //... do work
- sw.Stop();
- }
- // Example 2:
- {
- PerformanceStopWatch sw = PerformanceStopWatch.Start((duration)=>{
- Debug.WriteLine("Time: " + duration);
- });
- //... do work
- sw.Stop();
- }
- // Example 3:
- {
- using(PerformanceStopWatch sw = PerformanceStopWatch.Start((duration) => {
- Debug.WriteLine("Time: " + duration);
- })) {
- //... do work
- }//stop is called when PerformanceStopWatch->Dispose() is called
- }
- */
- /// </example>
- /// </summary>
- public class PerformanceStopWatch:IDisposable {
- public static PerformanceStopWatch Start(Action<TimeSpan> stopaction = null) {
- return new PerformanceStopWatch(stopaction);
- }
- readonly DateTime _started;
- Action<TimeSpan> _stopaction;
- TimeSpan _duration = TimeSpan.Zero;
- public PerformanceStopWatch(Action<TimeSpan> stopaction = null) {
- _stopaction = stopaction;
- _started = DateTime.Now;
- }
- public Action<TimeSpan> StopAction {
- get {
- return _stopaction;
- }
- set {
- _stopaction = value;
- }
- }
- public TimeSpan Duration {
- get {
- return _duration;
- }
- }
- public TimeSpan Stop() {
- _duration = DateTime.Now.Subtract(_started);
- if(_stopaction != null)
- _stopaction(_duration);
- return _duration;
- }
- public void Dispose() {
- Stop();
- }
- }
- }
Add Comment
Please, Sign In to add comment