Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

[Refactor] MigrateLibrarySymlinkTask and BaseTask

nzbdav-devc39010f78fde
diff --git a/backend/Tasks/BaseTask.cs b/backend/Tasks/BaseTask.cs
new file mode 100644
index 00000000..bb1ecaf5
--- /dev/null
+++ b/backend/Tasks/BaseTask.cs
@@ -0,0 +1,33 @@
+namespace NzbWebDAV.Tasks;
+
+public abstract class BaseTask
+{
+ protected abstract Task ExecuteInternal();
+
+ private static readonly SemaphoreSlim Semaphore = new(1, 1);
+ private static Task? _runningTask;
+
+ public async Task<bool> Execute()
+ {
+ await Semaphore.WaitAsync();
+ Task? task;
+ try
+ {
+ // if the task is already running, return immediately.
+ if (_runningTask is { IsCompleted: false })
+ return false;
+
+ // otherwise, run the task.
+ _runningTask = Task.Run(ExecuteInternal);
+ task = _runningTask;
+ }
+ finally
+ {
+ Semaphore.Release();
+ }
+
+ // and wait for it to finish.
+ await task;
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/backend/Tasks/MigrateLibrarySymlinksTask.cs b/backend/Tasks/MigrateLibrarySymlinksTask.cs
index 166be338..2386b987 100644
--- a/backend/Tasks/MigrateLibrarySymlinksTask.cs
+++ b/backend/Tasks/MigrateLibrarySymlinksTask.cs
@@ -12,36 +12,9 @@ public class MigrateLibrarySymlinksTask(
ConfigManager configManager,
WebsocketManager websocketManager,
DatabaseStore store
-)
+) : BaseTask
{
- private static readonly SemaphoreSlim Semaphore = new(1, 1);
- private static Task? _runningTask;
-
- public async Task<bool> Execute()
- {
- await Semaphore.WaitAsync();
- Task? task;
- try
- {
- // if the task is already running, return immediately.
- if (_runningTask is { IsCompleted: false })
- return false;
-
- // otherwise, run the task.
- _runningTask = Task.Run(ExecuteInternal);
- task = _runningTask;
- }
- finally
- {
- Semaphore.Release();
- }
-
- // and wait for it to finish.
- await task;
- return true;
- }
-
- private async Task ExecuteInternal()
+ protected override async Task ExecuteInternal()
{
try
{