TimingMeasure.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Diagnostics;
  3. using VCommon.Logging;
  4. namespace VCommon.Diagnostics
  5. {
  6. public class TimingMeasure : IDisposable
  7. {
  8. private readonly Stopwatch _stopwatch = new Stopwatch();
  9. public TimingMeasure()
  10. {
  11. _stopwatch.Start();
  12. }
  13. public void Dispose()
  14. {
  15. _stopwatch.Stop();
  16. MeasureResult(_stopwatch.ElapsedMilliseconds);
  17. }
  18. protected virtual void MeasureResult(long ms)
  19. {
  20. }
  21. }
  22. public class TimeoutWarnLog : TimingMeasure
  23. {
  24. private readonly object _details;
  25. public string Tag { get; }
  26. public int TimeoutMs { get; }
  27. public TimeoutWarnLog(string tag, int timeoutMs = 100, object details = null)
  28. {
  29. _details = details;
  30. Tag = tag;
  31. TimeoutMs = timeoutMs;
  32. }
  33. protected override void MeasureResult(long ms)
  34. {
  35. if (ms > TimeoutMs)
  36. Logger.Warn($"TimingMeasure Result:{Tag}", new { ms, details = _details });
  37. //else
  38. // Logger.Debug($"TimingMeasure Result:{Tag}", new { ms, details = _details });
  39. }
  40. }
  41. public class TimingMeasureAction : TimingMeasure
  42. {
  43. private readonly Action<long> _retrMs;
  44. public TimingMeasureAction(Action<long> retrMs)
  45. {
  46. _retrMs = retrMs;
  47. }
  48. protected override void MeasureResult(long ms)
  49. {
  50. _retrMs?.Invoke(ms);
  51. }
  52. }
  53. }