Falcon.SugarApi/Falcon.SugarApi.Test/BackTaskTest.cs

90 lines
3.0 KiB
C#

using Falcon.SugarApi.BackTask;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
namespace Falcon.SugarApi.Test
{
[TestClass]
public class BackTaskTest
{
[TestMethod]
public void BackgroundLongTaskTestMethod() {
var task = new BackTaskObject();
Assert.IsTrue(task.State == 0, "初始化状态错误");
var token = new CancellationTokenSource();
task.StartAsync(token.Token);
Thread.Sleep(1 * 1000);
Assert.IsTrue(task.State == 1, "启动状态错误");
Thread.Sleep(5 * 1000);
task.StopAsync(token.Token).Wait();
Thread.Sleep(2 * 1000);
Assert.IsTrue(task.State == 2, "停止状态错误");
Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")}:测试完成");
var asyncTask = new BackTaskAsync();
Console.WriteLine("启动异步任务");
asyncTask.StartAsync(token.Token).Wait();
Thread.Sleep(10 * 1000);
Console.WriteLine("停止异步任务");
asyncTask.StopAsync(token.Token).Wait();
}
}
public class BackTaskAsync : BackTaskObject
{
public BackTaskAsync() {
this.Log = new TestLog<BackTaskObject>();
}
public override float RunTimespan => 1;
protected async override Task<bool> RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:BackTaskAsync Run!");
//Thread.Sleep(3 * 1000);
await Task.Delay(new TimeSpan(0,0,3));
return true;
}
}
public class BackTaskObject : BackgroundLongTask
{
public override float RunTimespan => 1;
public ILogger Log { get; set; }
public int State { get; set; } = 0;
public BackTaskObject() {
this.Log = new TestLog<BackTaskObject>();
}
protected override void OnStop(BackgroundLongTask t) {
State = 2;
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test OnStop!");
base.OnStop(t);
}
protected override void OnStart(BackgroundLongTask t) {
State = 1;
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test OnStart!");
base.OnStart(t);
}
protected override void OnCompleted(BackgroundLongTask t) {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test OnCompleted!");
base.OnCompleted(t);
}
protected override Task<bool> RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test RunAsync!");
return Task.FromResult(true);
}
protected override bool Run() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test Run!");
return true;
}
}
}