Sobes.tech
Senior

How to synchronize access to a resource in asynchronous code (no more than one request at a time)?

sobes.tech AI

Answer from AI

To synchronize access to a resource in asynchronous C# code and ensure that no more than one request is executed at the same time, you can use the SemaphoreSlim class.

Example:

private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

public async Task UseResourceAsync()
{
    await _semaphore.WaitAsync();
    try
    {
        // Work with the resource
        await SomeAsyncOperation();
    }
    finally
    {
        _semaphore.Release();
    }
}

Here, SemaphoreSlim with a maximum count of 1 acts as an asynchronous mutex, allowing only one call to enter the critical section at a time. Other calls will wait for the semaphore to be released without blocking the thread.

How to synchronize access to a resource in… - sobes.tech