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;