Skip to content

Instantly share code, notes, and snippets.

@musoftware
Last active June 24, 2022 18:36
Show Gist options
  • Save musoftware/cc668a1063b0ce9e3fd2a0419eeb4382 to your computer and use it in GitHub Desktop.
Save musoftware/cc668a1063b0ce9e3fd2a0419eeb4382 to your computer and use it in GitHub Desktop.
While you make invoke to control from many many threads , the UI will hang
internal class AvoidHang : IDisposable
{
private readonly SemaphoreSlim _semaphore = new System.Threading.SemaphoreSlim(1, 1);
public void Dispose()
{
_semaphore.Dispose();
}
public void ToAvoidHang(int fast = 1000, Action action = null)
{
lock (this)
{
if (_semaphore.CurrentCount != 1) return;
_semaphore.Wait();
action?.Invoke();
(new Thread(() =>
{
Thread.Sleep(fast);
try
{
if (_semaphore.CurrentCount == 0)
_semaphore.Release();
}
catch (Exception)
{
// ignored
}
})).Start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment