Last active
June 24, 2022 18:36
-
-
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
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); | |
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