Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
}
like image 358
Grapes Avatar asked Jul 23 '13 05:07

Grapes


1 Answers

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();

 }
like image 179
ilansch Avatar answered Sep 27 '22 21:09

ilansch