C# async/await - Limit # of calls to async methods / locking

async-await, asynchronous, c#

Solution

You can use SemaphoreSlim(1) for this, A SemaphoreSlim created with (1) will make sure only one thread can get the lock, any other threads that try to get the lock - will wait until the one who got it - release it. create a private member:

private SemaphoreSlim _syncLock = new SemaphoreSlim(1);

Then in your code do:

async Task BasicProcess() {

     await _syncLock.WaitAsync(); //Only 1 thread can access the function or functions that use this lock, others trying to access - will wait until the first one released.
     //Do your stuff..
     _syncLock.Release();

 }

Problem

I come from C++ world so I am very used to locking threads and mutex guarding. Assuming this basic function: ``` async Task BasicProcess() { // await time consuming task } ``` How can I lock this function so only one `BasicProcess` can run at one time? This is what I want to achieve: ``` async Task BasicProcess() { lock (BasicProcessLock) { // await time consuming task } } ```

Original source