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
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With