From d66af3d6cd96335e6c28ab04305c78eebc0f3e5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BE=99=E8=85=BE=E7=8C=AB=E8=B7=83?= <1043137532@qq.com> Date: Tue, 23 Jun 2026 08:33:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=96=E6=B6=88=E5=BC=82=E5=B8=B8=E7=9B=B8?= =?UTF-8?q?=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Shared/Extensions/ExceptionExtensions.cs | 18 ++++++++++++++++++ Shared/General/Logger.cs | 4 ++-- Shared/Utils/ResilientUtils.cs | 4 ++-- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/Shared/Extensions/ExceptionExtensions.cs b/Shared/Extensions/ExceptionExtensions.cs index 1866669..e299736 100644 --- a/Shared/Extensions/ExceptionExtensions.cs +++ b/Shared/Extensions/ExceptionExtensions.cs @@ -11,6 +11,24 @@ public static class ExceptionExtensions { return ex; } + /// + /// 该异常或其子异常是否为 、 或 。 + /// + public static bool IsCanceled(this Exception ex) { + foreach (var inner in ex.Flatten()) { + if (inner is OperationCanceledException or TaskCanceledException or ThreadInterruptedException) return true; + } + return false; + } + /// + /// 当该异常或其子异常是 、 或 时,抛出对应异常。 + /// + public static void ThrowOnCanceled(this Exception ex) { + foreach (var inner in ex.Flatten()) { + if (inner is OperationCanceledException or TaskCanceledException or ThreadInterruptedException) throw inner; + } + } + /// /// 将异常所有的 展开。 /// 若为 ,也会展开其中所有的子异常。 diff --git a/Shared/General/Logger.cs b/Shared/General/Logger.cs index ce7370f..c759d5a 100644 --- a/Shared/General/Logger.cs +++ b/Shared/General/Logger.cs @@ -184,8 +184,8 @@ public class BaseLogger { // 核心方法 public virtual void Log(Exception? ex, string? message, LogLevel level, LogBehavior behavior, string filePath) { - if (ex is ThreadInterruptedException) { - Thread.CurrentThread.Interrupt(); + if (ex?.IsCanceled() == true) { + Log(null, $"操作已取消({message})", LogLevel.Info, LogBehavior.None, filePath); return; } if (MinLevel > level) return; diff --git a/Shared/Utils/ResilientUtils.cs b/Shared/Utils/ResilientUtils.cs index e85bc3f..220afab 100644 --- a/Shared/Utils/ResilientUtils.cs +++ b/Shared/Utils/ResilientUtils.cs @@ -34,7 +34,7 @@ public static class ResilientUtils { attempt++; if (attempt < maxAttempts) { Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,将在 {delayMs}ms 后重试"); - Thread.Sleep(delayMs); + if (delayMs > 0) Thread.Sleep(delayMs); } else { // 超过最大尝试次数 Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,已到达最大尝试次数"); throw; @@ -54,7 +54,7 @@ public static class ResilientUtils { attempt++; if (attempt < maxAttempts) { Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,将在 {delayMs}ms 后重试"); - Thread.Sleep(delayMs); + if (delayMs > 0) Thread.Sleep(delayMs); } else { // 超过最大尝试次数 Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,已到达最大尝试次数"); throw;