簡體   English   中英

C#async / await - 限制對異步方法/鎖定的調用次數

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

我來自C ++世界所以我非常習慣鎖定線程和互斥鎖防護。 假設這個基本功能:

async Task BasicProcess() {
    // await time consuming task
}

如何鎖定此功能,以便一次只能運行一個BasicProcess

這就是我想要實現的目標:

async Task BasicProcess() {
    lock (BasicProcessLock) {
         // await time consuming task
    }
}

你可以使用SemaphoreSlim(1),用(1)創建的SemaphoreSlim將確保只有一個線程可以獲得鎖定,任何其他嘗試獲取鎖定的線程 - 將等到獲得鎖定的線程 - 釋放它。
創建一個私有成員:

private SemaphoreSlim _syncLock = new SemaphoreSlim(1);

然后在你的代碼中做:

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