后台任务异步化

This commit is contained in:
falcon 2022-04-01 15:52:10 +08:00
parent 3333e7f12c
commit 4077501379
2 changed files with 11 additions and 9 deletions

View File

@ -28,23 +28,23 @@ namespace Falcon.SugarApi.Test
var asyncTask = new BackTaskAsync();
Console.WriteLine("启动异步任务");
asyncTask.StartAsync(token.Token).Wait();
Thread.Sleep(5 * 1000);
Thread.Sleep(10 * 1000);
Console.WriteLine("停止异步任务");
asyncTask.StopAsync(token.Token).Wait();
}
}
public class BackTaskAsync : BackgroundLongTask
public class BackTaskAsync : BackTaskObject
{
public BackTaskAsync() {
this.Log = new TestLog<BackTaskObject>();
}
public ILogger Log { get; set; }
public override float RunTimespan => 1;
protected async override void Run() {
protected async override Task RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:BackTaskAsync Run!");
//Thread.Sleep(3 * 1000);
await Task.Delay(new TimeSpan(0,0,3));
await Task.CompletedTask;
}
}
@ -76,8 +76,9 @@ namespace Falcon.SugarApi.Test
base.OnCompleted(t);
}
protected override void Run() {
protected override Task RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test Run!");
return Task.CompletedTask;
}
}

View File

@ -13,9 +13,9 @@ namespace Falcon.SugarApi.BackTask
/// <summary>
/// 要执行的任务
/// </summary>
protected abstract void Run();
protected abstract Task RunAsync();
/// <summary>
/// 执行时间间隔
/// 执行时间间隔,秒
/// </summary>
public abstract float RunTimespan { get; }
/// <summary>
@ -46,7 +46,8 @@ namespace Falcon.SugarApi.BackTask
OnStart(this);
while (!TokenSource.Token.IsCancellationRequested) {
await Task.Delay(TimeSpan.FromSeconds(RunTimespan))
.ContinueWith(wt => { Run(); }).ContinueWith(wt => OnCompleted(this));
.ContinueWith(_ => { RunAsync().Wait(); })
.ContinueWith(_ => OnCompleted(this));
}
OnStop(this);
};