What is wrong with locking non-static fields? What is the correct way to lock a particular instance?
Posted
by
smartcaveman
on Stack Overflow
See other posts from Stack Overflow
or by smartcaveman
Published on 2011-02-12T15:15:44Z
Indexed on
2011/02/12
15:25 UTC
Read the original article
Hit count: 243
Why is it considered bad practice to lock non-static fields?
And, if I am not locking non-static fields, then how do I lock an instance method without locking the method on all other instances of the same or derived class?
I wrote an example to make my question more clear.
public abstract class BaseClass
{
private readonly object NonStaticLockObject = new object();
private static readonly object StaticLockObject = new object();
protected void DoThreadSafeAction<T>(Action<T> action)
where T: BaseClass
{
var derived = this as T;
if(derived == null)
{
throw new Exception();
}
lock(NonStaticLockObject)
{
action(derived);
}
}
}
public class DerivedClass :BaseClass
{
private readonly Queue<object> _queue;
public void Enqueue(object obj)
{
DoThreadSafeAction<DerivedClass>(x=>x._queue.Enqueue(obj));
}
}
If I make the lock on the StaticLockObject
, then the DoThreadSafeAction
method will be locked for all instances of all classes that derive from BaseClass
and that is not what I want. I want to make sure that no other threads can call a method on a particular instance of an object while it is locked.
© Stack Overflow or respective owner