Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SemaphoreLockDisposable.cs - github.com/ClusterM/tuyanet.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9d4ec6394e99de32c69620c6cd143840e5f5cc9c (plain)
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
38
39
40
using System;
using System.Threading;
using System.Threading.Tasks;

namespace com.clusterrr.SemaphoreLock
{
    public static class SemaphoreSlimSimple
    {
        public static SemaphoreLock WaitDisposable(this SemaphoreSlim semaphore)
        {
            var l = new SemaphoreLock(semaphore);
            semaphore.Wait();
            //GC.KeepAlive(l);
            return l;
        }

        public static async Task<SemaphoreLock> WaitDisposableAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
        {
            var l = new SemaphoreLock(semaphore);
            await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
            //GC.KeepAlive(l);
            return l;
        }
    }

    public class SemaphoreLock : IDisposable
    {
        readonly SemaphoreSlim lockedSemaphore;

        public SemaphoreLock(SemaphoreSlim lockedSemaphore)
        {
            this.lockedSemaphore = lockedSemaphore;
        }

        public void Dispose()
        {
            lockedSemaphore.Release();
        }
    }
}