Created
October 25, 2022 11:23
-
-
Save musoftware/6bad10bcb49376137ead466691038258 to your computer and use it in GitHub Desktop.
New Avoid Hang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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