我有一个可以更改内部状态的类。为异步应用设计的锁
这些状态变化是决不简单,并且通常由在多个线程中发生几个异步操作,如打开的连接,并发送一些数据
通过使用锁定和一个布尔值,指示所述状态是否是目前改变我可以确保只有一个操作都不能在任何给定的时间
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