From b2f2ab4fa51fddc0fc2cf8aa00dbd1fddc20d2d3 Mon Sep 17 00:00:00 2001 From: GeWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Sat, 14 Feb 2026 19:16:34 +0800 Subject: [PATCH] =?UTF-8?q?perf(cqrs):=20=E4=BC=98=E5=8C=96=E6=80=A7?= =?UTF-8?q?=E8=83=BD=E8=A1=8C=E4=B8=BA=E4=B8=AD=E7=9A=84=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将同步方法改为异步方法以正确处理异步操作 - 使用 Stopwatch.GetTimestamp() 替代 StartNew() 提高计时精度 - 通过 try-finally 确保即使在异常情况下也能正确计算执行时间 - 改进长时间运行请求的日志记录机制 - 使用 Elapsed.TotalMilliseconds 替代 ElapsedMilliseconds 并保留两位小数 - 保持 500 毫秒阈值不变,只对超时请求记录警告日志 --- .../cqrs/behaviors/PerformanceBehavior.cs | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/GFramework.Core/cqrs/behaviors/PerformanceBehavior.cs b/GFramework.Core/cqrs/behaviors/PerformanceBehavior.cs index f4a4da0..5f16e01 100644 --- a/GFramework.Core/cqrs/behaviors/PerformanceBehavior.cs +++ b/GFramework.Core/cqrs/behaviors/PerformanceBehavior.cs @@ -38,22 +38,27 @@ public sealed class PerformanceBehavior : IPipelineBehavior /// 下一个处理委托,用于继续管道执行 /// 取消令牌,用于取消操作 /// 处理结果的ValueTask - public ValueTask Handle(TRequest message, MessageHandlerDelegate next, + public async ValueTask Handle( + TRequest message, + MessageHandlerDelegate next, CancellationToken cancellationToken) { - var stopwatch = Stopwatch.StartNew(); + var start = Stopwatch.GetTimestamp(); - var response = next(message, cancellationToken); + try + { + return await next(message, cancellationToken); + } + finally + { + var elapsed = Stopwatch.GetElapsedTime(start); - stopwatch.Stop(); - - var elapsedMilliseconds = stopwatch.ElapsedMilliseconds; - - // 只有当执行时间超过500毫秒时才记录警告日志 - if (elapsedMilliseconds <= 500) return response; - var requestName = typeof(TRequest).Name; - _logger.Warn($"Long Running Request: {requestName} ({elapsedMilliseconds} ms)"); - - return response; + if (elapsed.TotalMilliseconds > 500) + { + var requestName = typeof(TRequest).Name; + _logger.Warn( + $"Long Running Request: {requestName} ({elapsed.TotalMilliseconds:F2} ms)"); + } + } } } \ No newline at end of file