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

85 lines
2.8 KiB
C#
Raw Normal View History

2022-03-21 12:05:12 +08:00
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;
2022-03-21 12:05:12 +08:00
namespace Falcon.SugarApi.Test
{
[TestClass]
public class BackTaskTest
{
[TestMethod]
public void BackgroundLongTaskTestMethod() {
var task = new BackTaskObject();
Assert.IsTrue(task.State == 0, "<22><>ʼ<EFBFBD><CABC>״̬<D7B4><CCAC><EFBFBD><EFBFBD>");
var token = new CancellationTokenSource();
task.StartAsync(token.Token);
Thread.Sleep(1 * 1000);
Assert.IsTrue(task.State == 1, "<22><><EFBFBD><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD>");
Thread.Sleep(5 * 1000);
task.StopAsync(token.Token).Wait();
Thread.Sleep(2 * 1000);
Assert.IsTrue(task.State == 2, "ֹͣ״̬<D7B4><CCAC><EFBFBD><EFBFBD>");
Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")}:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
var asyncTask = new BackTaskAsync();
Console.WriteLine("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><ECB2BD><EFBFBD><EFBFBD>");
asyncTask.StartAsync(token.Token).Wait();
2022-04-01 15:52:10 +08:00
Thread.Sleep(10 * 1000);
Console.WriteLine("ֹͣ<CDA3><EFBFBD><ECB2BD><EFBFBD><EFBFBD>");
asyncTask.StopAsync(token.Token).Wait();
}
}
2022-04-01 15:52:10 +08:00
public class BackTaskAsync : BackTaskObject
{
public BackTaskAsync() {
this.Log = new TestLog<BackTaskObject>();
}
public override float RunTimespan => 1;
2022-04-01 15:52:10 +08:00
protected async override Task RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:BackTaskAsync Run!");
2022-04-01 15:52:10 +08:00
//Thread.Sleep(3 * 1000);
await Task.Delay(new TimeSpan(0,0,3));
await Task.CompletedTask;
2022-03-21 12:05:12 +08:00
}
}
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>();
2022-03-21 12:05:12 +08:00
}
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);
}
2022-04-01 15:52:10 +08:00
protected override Task RunAsync() {
2022-03-21 12:05:12 +08:00
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test Run!");
2022-04-01 15:52:10 +08:00
return Task.CompletedTask;
2022-03-21 12:05:12 +08:00
}
}
}