Possible Duplicate:
Difference between lock(locker) and lock(variable_which_I_am_using)
In all of the "thread-safe" code examples i've seen, they lock on a separate dummy object. Why cant locks be directly performed on the data in question?
The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.
Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.
The lock statement is one of the simplest and most common tools for C# developers writing multithreaded applications. It can be used to synchronize access to blocks of code, achieving thread safety by allowing only one thread at a time to execute the code in that block.
Locking on a separate private
dummy object gives you a guarantee that no one else is locking in that object.
If you lock on the data and that same piece of data is visible to the outside you lose that guarantee. For example:
public class MyObject
{
public void SharedMethod()
{
lock (this)
{
// Do stuff
}
}
}
class Program
{
static void Main(string[] args)
{
MyObject o = new MyObject();
lock (o)
{
new Thread(() =>
{
// Gets blocked 2s because of external lock
o.SharedMethod();
}).Start();
Thread.Sleep(2000);
}
}
}
Jeff Richter (author of CLR Via C#) explains why in this article on Safe Thread Synchronization.
Specifically, in that article the section "Why the Great Idea isn't So Great" answers your question.
It's actually a chapter from the book CLR Via C#.
In summary, having a private object as the "synclock" object allows your class to encapsulate and control any locking your class needs. Therefore regardless of how many clients use your class, locking is performed consistently and correctly.
There's some great stuff on this on Eric Gunnerson's blog. See here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With