Home »

How do I prevent concurrent access to my data?

Question ListCategory: ASP.NETHow do I prevent concurrent access to my data?
jamessmith05 author asked 8 years ago
1 Answers
milleranthony7 author answered 8 years ago

Each object has a concurrency lock (critical section) associated with it. TheSystem.Threading.Monitor.Enter/Exit methods are used to acquire and
release this lock. For example, instances of the following class only allow one
thread at a time to enter method f():
class C{
public void f(){
try{
Monitor.Enter(this);

}
finally{
Monitor.Exit(this);
}
}
}
C# has a ‘lock’ keyword which provides a convenient shorthand for the code
above:
class C{
public void f(){
lock(this){

}
}
}
Note that calling Monitor.Enter(myObject) does NOT mean that all access to
myObject is serialized. It means that the synchronisation lock associated with
myObject has been acquired, and no other thread can acquire that lock until
Monitor.Exit(o) is called. In other words, this class is functionally equivalent
to the classes above:
class C{
public void f(){
lock( m_object ){

}
}
private m_object = new object();
}
Satish Marwat Dot Net Web Resources satishcm@gmail.com 39 Page
Actually, it could be argued that this version of the code is superior, as the
lock is totally encapsulated within the class, and not accessible to the user of
the object.

Please login or Register to Submit Answer