2013-07-23 132 views
10

我來自C++世界,所以我非常習慣於鎖定線程和互斥鎖。假設這個基本功能:C#異步/等待 - 限制異步方法調用/鎖定

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

怎樣才能鎖定這個功能,所以只有一個BasicProcess可以在同一時間運行?

這就是我想要達到的目標:

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

見http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988 .aspx的AsyncLock實現。 –

回答

29

您可以使用SemaphoreSlim(1)對於這一點,與創建的SemaphoreSlim(1)將確保只有一個線程能夠獲得鎖,任何其他線程試圖獲得鎖定 - 將等到獲得鎖定的人釋放鎖定。
創建一個私有成員:

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

} 
+2

除了現在會阻止調用線程,這並不理想,如果它真的是異步的。 –

+0

更好地使用「await _syncLock.WaitAsync();」 - 否則,線程將被阻塞,任務將不會運行。 – jlahd

+0

Jon/jlahd - 謝謝你的更新,以免阻擋。 – ilansch