Nó rất hữu ích để đẩy mã điểm chuẩn của bạn thành một lớp tiện ích / phương pháp. Các StopWatchlớp không cần phải Disposedhoặc Stoppedvề lỗi. Vì vậy, mã đơn giản nhất để thực hiện một số hành động là
public partial class With
{
public static long Benchmark(Action action)
{
var stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
}
Mã gọi mẫu
public void Execute(Action action)
{
var time = With.Benchmark(action);
log.DebugFormat(“Did action in {0} ms.”, time);
}
Đây là phiên bản phương thức mở rộng
public static class Extensions
{
public static long Benchmark(this Action action)
{
return With.Benchmark(action);
}
}
Và mã gọi mẫu
public void Execute(Action action)
{
var time = action.Benchmark()
log.DebugFormat(“Did action in {0} ms.”, time);
}