naps2/NAPS2.Escl.Server/SimpleAsyncLock.cs
Ben Olden-Cooligan 2c51b28078 Escl: Improve reliability through network interruptions
- Use backported SocketsHttpHandler
- Set a ConnectTimeout of 5s
- Lock while processing NextDocument requests
- NextDocument responds with the same document on retries after error

#336
2024-03-31 18:33:22 -07:00

37 lines
823 B
C#

namespace NAPS2.Escl.Server;
internal class SimpleAsyncLock
{
private readonly Queue<TaskCompletionSource<bool>> _listeners = new();
private bool _isTaken;
public Task Take()
{
lock (this)
{
if (!_isTaken)
{
_isTaken = true;
return Task.CompletedTask;
}
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_listeners.Enqueue(tcs);
return tcs.Task;
}
}
public void Release()
{
lock (this)
{
if (_listeners.Count > 0)
{
_listeners.Dequeue().SetResult(true);
}
else
{
_isTaken = false;
}
}
}
}