简体   繁体   English

C#async / await - 限制对异步方法/锁定的调用次数

[英]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. 我来自C ++世界所以我非常习惯锁定线程和互斥锁防护。 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? 如何锁定此功能,以便一次只能运行一个BasicProcess

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. 你可以使用SemaphoreSlim(1),用(1)创建的SemaphoreSlim将确保只有一个线程可以获得锁定,任何其他尝试获取锁定的线程 - 将等到获得锁定的线程 - 释放它。
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();

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM