perf(cqrs): 优化性能行为中的请求处理逻辑

- 将同步方法改为异步方法以正确处理异步操作
- 使用 Stopwatch.GetTimestamp() 替代 StartNew() 提高计时精度
- 通过 try-finally 确保即使在异常情况下也能正确计算执行时间
- 改进长时间运行请求的日志记录机制
- 使用 Elapsed.TotalMilliseconds 替代 ElapsedMilliseconds 并保留两位小数
- 保持 500 毫秒阈值不变,只对超时请求记录警告日志
This commit is contained in:
GeWuYou 2026-02-14 19:16:34 +08:00 committed by gewuyou
parent 276f50a255
commit b2f2ab4fa5

View File

@ -38,22 +38,27 @@ public sealed class PerformanceBehavior<TRequest, TResponse> : IPipelineBehavior
/// <param name="next">下一个处理委托,用于继续管道执行</param>
/// <param name="cancellationToken">取消令牌,用于取消操作</param>
/// <returns>处理结果的ValueTask</returns>
public ValueTask<TResponse> Handle(TRequest message, MessageHandlerDelegate<TRequest, TResponse> next,
public async ValueTask<TResponse> Handle(
TRequest message,
MessageHandlerDelegate<TRequest, TResponse> 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)");
}
}
}
}