后台任务发生异常时增加默认异常处理,并实现了异常退出机制

This commit is contained in:
Falcon 2025-02-24 10:56:38 +08:00
parent cdfedb4c6b
commit 3560ab0e54

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@ -65,10 +66,14 @@ namespace Falcon.SugarApi.TimedBackgroundTask
/// </summary>
protected virtual void OnCompleted(TimedTask t,CancellationToken stoppingToken) { }
/// <summary>
/// 执行中发生未处理异常
/// 执行中发生未处理异常。返回True任务会继续执行False则任务退出。
/// </summary>
protected virtual bool OnException(TimedTask t,Exception ex,CancellationToken stoppingToken) {
return false;
StringBuilder sb = new();
sb.AppendLine($"运行后台任务发生未处理的异常,后台任务会继续执行,异常信息可能会重复出现!");
sb.AppendLine(ex.ToString());
this.Logger?.LogError(sb.ToString());
return true;
}
/// <summary>
/// 系统服务
@ -115,7 +120,9 @@ namespace Falcon.SugarApi.TimedBackgroundTask
}
}
catch(Exception ex) {
this.OnException(this,ex,stoppingToken);
if(!this.OnException(this,ex,stoppingToken)) {
break;
}
}
SetNextTick();
this._isRunning = false;