Skip to content

Instantly share code, notes, and snippets.

@musoftware
Created October 25, 2022 11:23
Show Gist options
  • Save musoftware/6bad10bcb49376137ead466691038258 to your computer and use it in GitHub Desktop.
Save musoftware/6bad10bcb49376137ead466691038258 to your computer and use it in GitHub Desktop.
New Avoid Hang
internal class AvoidHang : IDisposable
{
private readonly SemaphoreSlim _semaphore = new System.Threading.SemaphoreSlim(1, 1);
Stopwatch stopwatch = new Stopwatch();
bool _started = true;
public AvoidHang(int fast = 1000)
{
stopwatch.Start();
(new Thread(() =>
{
while (_started)
{
Thread.Sleep(fast);
try
{
if (_semaphore.CurrentCount == 0)
_semaphore.Release();
}
catch (Exception)
{
// ignored
}
}
})).Start();
}
public void Dispose()
{
_started = false;
_semaphore.Dispose();
}
public void ToAvoidHang(Action action = null)
{
lock (this)
{
if (_semaphore.CurrentCount != 1) return;
_semaphore.Wait();
action?.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment