Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace System {
- /// <summary>
- /// General stop watch with callback delegates
- /// </summary>
- public class StopWatch:IDisposable {
- public const string NUMBER_FORMAT = "#,#";
- //StopWatch.GlobalDurationCallBack += new Action<TimeSpan,string>((duration,name) => {
- // //do something
- //});
- public static Action<TimeSpan,string> GlobalDurationCallBack { get; set; }
- #region Static Create()
- public static StopWatch Create() {
- return new StopWatch(GlobalDurationCallBack);
- }
- public static StopWatch Create(string name) {
- return new StopWatch(GlobalDurationCallBack) { Name = name };
- }
- public static StopWatch Create(string name,Action<TimeSpan,string> durationCallBack) {
- return new StopWatch(name,durationCallBack);
- }
- public static StopWatch Create(Action<TimeSpan,string> durationCallBack) {
- return new StopWatch(durationCallBack);
- }
- #endregion
- long _start;
- TimeSpan _duration;
- Action<TimeSpan,string> _durationCallBack;
- string _name;
- public string Name {
- get { return _name; }
- set { _name = value; }
- }
- public TimeSpan Duration {
- get { return _duration; }
- }
- #region ctr
- public StopWatch()
- : this(null,GlobalDurationCallBack,true) {
- }
- public StopWatch(string name)
- : this(name,GlobalDurationCallBack,true) {
- }
- public StopWatch(string name,Action<TimeSpan,string> durationCallBack)
- : this(name,durationCallBack,true) {
- }
- public StopWatch(Action<TimeSpan,string> durationCallBack)
- : this(null,durationCallBack,true) {
- }
- public StopWatch(Action<TimeSpan,string> durationCallBack,bool startStopWatch)
- : this(null,durationCallBack,startStopWatch) {
- }
- public StopWatch(bool startStopWatch)
- : this(null,GlobalDurationCallBack,startStopWatch) {
- }
- public StopWatch(string name,Action<TimeSpan,string> durationCallBack,bool startStopWatch) {
- _name = name;
- _durationCallBack = durationCallBack;
- Reset();
- if(startStopWatch)
- Start();
- }
- #endregion
- public void Reset() {
- _duration = TimeSpan.Zero;
- _start = 0;
- }
- public void Start() {
- Reset();
- _start = DateTime.Now.Ticks;
- }
- public TimeSpan Stop() {
- if(_duration == TimeSpan.Zero) {
- long end = DateTime.Now.Ticks;
- _duration = new TimeSpan(end - _start);
- }
- if(_durationCallBack != null)
- _durationCallBack(_duration,_name);
- return _duration;
- }
- public override string ToString() {
- return ToString(NUMBER_FORMAT);
- }
- public string ToString(string millisecondsFormat) {
- double totalMilliseconds = -1.0D;
- if(Duration != TimeSpan.Zero)
- totalMilliseconds = Duration.TotalMilliseconds;
- return totalMilliseconds.ToString(millisecondsFormat);
- }
- public void Dispose() {
- Stop();
- }
- }
- }
Add Comment
Please, Sign In to add comment