2024-04-16 18:19:05 +02:00
|
|
|
using System;
|
|
|
|
using System.Threading;
|
|
|
|
|
2024-08-31 18:56:48 +02:00
|
|
|
namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
|
2024-04-16 18:19:05 +02:00
|
|
|
|
|
|
|
internal sealed class ScheduledTaskSemaphore : IDisposable
|
|
|
|
{
|
2024-09-10 18:08:42 +02:00
|
|
|
private static readonly SemaphoreSlim _semaphore = new(1, 1);
|
2024-04-16 18:19:05 +02:00
|
|
|
|
2024-09-10 18:08:42 +02:00
|
|
|
private static bool _isHeld;
|
2024-05-10 06:35:52 +02:00
|
|
|
|
2024-04-16 18:19:05 +02:00
|
|
|
private ScheduledTaskSemaphore()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public static int CurrentCount => _semaphore.CurrentCount;
|
|
|
|
|
2024-05-10 06:35:52 +02:00
|
|
|
public static IDisposable Acquire(int timeout, CancellationToken cancellationToken)
|
2024-04-16 18:19:05 +02:00
|
|
|
{
|
2024-05-10 06:35:52 +02:00
|
|
|
_isHeld = _semaphore.Wait(timeout, cancellationToken);
|
|
|
|
return new ScheduledTaskSemaphore();
|
2024-04-16 18:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Dispose.
|
|
|
|
/// </summary>
|
|
|
|
public void Dispose()
|
|
|
|
{
|
2024-05-10 06:35:52 +02:00
|
|
|
if (_isHeld) // Release only if acquired
|
2024-04-16 18:19:05 +02:00
|
|
|
{
|
2024-05-10 06:35:52 +02:00
|
|
|
_semaphore.Release();
|
|
|
|
_isHeld = false;
|
2024-04-16 18:19:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|