<PackageReference Include="Polly" Version="8.3.1" />

TimedLock

using System; using System.Runtime.CompilerServices; using System.Threading; namespace Polly.Utilities { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] internal readonly struct TimedLock : IDisposable { private static readonly TimeSpan LockTimeout = TimeSpan.FromMilliseconds(2147483647); private readonly object _target; public static TimedLock Lock(object o) { return Lock(o, LockTimeout); } private static TimedLock Lock(object o, TimeSpan timeout) { TimedLock result = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) throw new LockTimeoutException(); return result; } private TimedLock(object o) { _target = o; } public void Dispose() { Monitor.Exit(_target); } } }