1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2025-08-16 21:31:45 +02:00
Files
.config
.run
.workdir
Agent
Common
Controller
Docker
Utils
Phantom.Utils
Collections
Cryptography
IO
Processes
Result
Runtime
Tasks
AsyncTasks.cs
CancellableBackgroundTask.cs
Throttler.cs
Threading
Phantom.Utils.csproj
Phantom.Utils.Actor
Phantom.Utils.Events
Phantom.Utils.Logging
Phantom.Utils.Rpc
Phantom.Utils.Tests
Web
.dockerignore
.gitattributes
.gitignore
AddMigration.bat
AddMigration.sh
Directory.Build.props
Directory.Build.targets
Dockerfile
LICENSE
Packages.props
PhantomPanel.sln
README.md
global.json

48 lines
1014 B
C#

using Serilog;
namespace Phantom.Utils.Tasks;
public abstract class CancellableBackgroundTask {
private readonly CancellationTokenSource cancellationTokenSource = new ();
protected ILogger Logger { get; }
protected CancellationToken CancellationToken { get; }
protected CancellableBackgroundTask(ILogger logger) {
this.Logger = logger;
this.CancellationToken = cancellationTokenSource.Token;
}
protected void Start() {
Task.Run(Run, CancellationToken.None);
}
private async Task Run() {
Logger.Debug("Task started.");
try {
await RunTask();
} catch (OperationCanceledException) {
// Ignore.
} catch (Exception e) {
Logger.Fatal(e, "Caught exception in task.");
} finally {
cancellationTokenSource.Dispose();
Dispose();
Logger.Debug("Task stopped.");
}
}
protected abstract Task RunTask();
protected abstract void Dispose();
public void Stop() {
try {
cancellationTokenSource.Cancel();
} catch (ObjectDisposedException) {
// Ignore.
}
}
}