Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locking the object inside a property, c#

Tags:

c#

public ArrayList InputBuffer
{
    get { lock (this.in_buffer) { return this.in_buffer; } }
}

is this.in_buffer locked during a call to InputBuffer.Clear?

or does the property simply lock the in_buffer object while it's getting the reference to it; the lock exits, and then that reference is used to Clear?

like image 687
paIncrease Avatar asked Dec 28 '22 01:12

paIncrease


1 Answers

No, the property locks the reference while it's getting that reference. Pretty pointless, to be honest... this is more common:

private readonly object mutex = new object();
private Foo foo = ...;

public Foo Foo
{
    get
    {
        lock(mutex)
        {
            return foo;
        }
    }
}

That lock would only cover the property access itself, and wouldn't provide any protection for operations performed with the Foo. However, it's not the same as not having the lock at all, because so long as the variable is only written while holding the same lock, it ensures that any time you read the Foo property, you're accessing the most recent value of the property... without the lock, there's no memory barrier and you could get a "stale" result.

This is pretty weak, but worth knowing about.

Personally I try to make very few types thread-safe, and those tend to have more appropriate operations... but if you wanted to write code which did modify and read properties from multiple threads, this is one way of doing so. Using volatile can help too, but the semantics of it are hideously subtle.

like image 121
Jon Skeet Avatar answered Jan 09 '23 05:01

Jon Skeet