namespace Febe.Core.Library.Conversion;
///
/// One conversion at a time across the process (tappa E3, decision D16): a photo conversion holds a decoded picture
/// and its encoder state (up to about a gigabyte for 40 megapixels), so the export and the library conversion take
/// turns, each off the calling thread.
///
public sealed class ConversionThrottle
{
private readonly SemaphoreSlim gate = new(1, 1);
/// The throttle every conversion of the process shares.
public static ConversionThrottle Shared { get; } = new();
/// Runs on the thread pool once no other conversion runs.
public async Task RunAsync(Func work, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(work);
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await Task.Run(() => work(ct), ct).ConfigureAwait(false);
}
finally
{
gate.Release();
}
}
}