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

TimedLock

using System; using System.Threading; namespace Polly.Utilities { internal struct TimedLock : IDisposable { private object target; public static TimedLock Lock(object o) { return Lock(o, TimeSpan.FromSeconds(5)); } public 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); } } }