How to limit number of threads in c#

How to limit number of threads in c#

I often use SemaphoreSlim which is a useful utility in .Net and support async await. Below are simple codes which use an extension to ensure that the limited number of threads.

Semaphore Slim


public static class SemaphoreSlimExtensions
{
    public static async Task<IDisposable> UseWaitAsync(
        this SemaphoreSlim semaphoreSlim, 
        CancellationToken cancelToken = default(CancellationToken)
    )
    {
        await semaphore.WaitAsync(cancelToken).ConfigureAwait(false);
        return new MySemaphore(semaphoreSlim);
    }
 
    private class MySemaphore : IDisposable
    {
        private readonly SemaphoreSlim _semaphoreSlim;
        private bool _isDisposed;
 
        public MySemaphore(SemaphoreSlim semaphoreSlim)
        {
            _semaphoreSlim = semaphoreSlim;
        }
 
        public void Dispose()
        {
            if (_isDisposed)
                return;
 
            _semaphoreSlim.Release();
            _isDisposed = true;
        }
    }
}

Using

public class SemaphoreSlimExtensionsTests
{
    [Fact]
    public async Task UseWaitAsync_CountSuccess()
    {
        var semaphoreSlim = new SemaphoreSlim(1, 1);
        Assert.Equal(1, semaphoreSlim.CurrentCount);
 
        using (await semaphoreSlim.UseWaitAsync())
        {
            Assert.Equal(0, semaphoreSlim.CurrentCount);
        }
 
        Assert.Equal(1, semaphoreSlim.CurrentCount);
    }
}