forked from ZeraGmbH/Blockly.Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SemaphoreExtensions.cs
37 lines (33 loc) · 1.15 KB
/
SemaphoreExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
namespace BlocklyNet.Scripting.Engine;
/// <summary>
///
/// </summary>
public static class SemaphoreExtensions
{
/// <summary>
/// Helper to wait on a semaphore to synchronize data flow.
/// </summary>
private class Waiter : IDisposable
{
/// <summary>
/// Semaphore to wait on.
/// </summary>
private Semaphore? _semaphore;
/// <summary>
/// Create wait in the semaphore.
/// </summary>
/// <param name="semaphore">Semaphore to use.</param>
public Waiter(Semaphore semaphore) => (_semaphore = semaphore)?.WaitOne();
/// <summary>
/// Release semaphore once - although this should never happen
/// disposing is safely protected against multi-use.
/// </summary>
public void Dispose() => Interlocked.Exchange(ref _semaphore, null)?.Release();
}
/// <summary>
/// Extension method to wait on a sempahore.
/// </summary>
/// <param name="semaphore">Semaphore to wait on.</param>
/// <returns>Waiting helper instance.</returns>
public static IDisposable Wait(this Semaphore semaphore) => new Waiter(semaphore);
}