我有一個可以更改內部狀態的類。爲異步應用設計的鎖
這些狀態變化是決不簡單,並且通常由在多個線程中發生幾個異步操作,如打開的連接,併發送一些數據
通過使用鎖定和一個布爾值,指示所述狀態是否是目前改變我可以確保只有一個操作都不能在任何給定的時間
lock (thisLock) {
while (stateChanging)
Monitor.Wait(thisLock);
stateChanging= true;
//now free to go away and do other things while maintaining exclusive access to the inner state
}
這工作得很好,獲得了國家,但它意味着在線程出現等待獲得獨家獲得的國家不必要的阻塞
所以我設想是基於回調,其中狀態改變操作鎖不這樣的事情 -
sharedLock.ObtainLock(delegate() {
//we now have exclusive access to the state
//do some work
socket = new Socket();
socket.BeginConnect(hostname, connectcallback);
});
void connectcallback(IAsyncResult result) {
socket.EndConnect(result);
isConnected = true;
sharedLock.ReleaseLock();
}
就是這樣一個概念,什麼共同點?它有名字嗎?我錯誤地接近事物嗎?
這很有用,謝謝 – NoPyGod
很高興幫助;) – Matthias