views:

201

answers:

2

I've got a class that manages a shared resource. Now, since access to the resource depends on many parameters, this class is instantiated and disposed several times during the normal execution of the program.

The shared resource does not support concurrency, so some kind of locking is needed. The first thing that came into my mind is having a static instance in the class, and acquire locks on it, like this:

// This thing is static!
static readonly object MyLock = new object();

// This thing is NOT static!
MyResource _resource = ...;

public DoSomeWork() {
    lock(MyLock) {
        _resource.Access();
    }
}

Does that make sense, or would you use another approach?

+3  A: 

Yes you can use a static variable to protect a shared resource.

You could also use typeof(class) as the expression inside lock. See the warning below though, with the static variable it is at least more protected to within your class.

Brian R. Bondy
I wouldn't lock on typeof(class), since you could get a deadlock if someone else locks on the same type. At least, don't do it on public types.
driis
@driis: Agreed, added a note in the answer. Thanks.
Brian R. Bondy
+1 for the "Yes you can...", -1 for the suggestion of locking on `typeof(class)`, so an aggregate 0.
LukeH
@Luke: No +1 for the post with the pinkest unicorn?
Brian R. Bondy
Maybe I've got some repressed, subconscious unicorn-jealousy going on!
LukeH
A: 

That's completely acceptable with the Lock on the static variable. You could also do

[ThreadStatic]
static readonly object MyLock = new object();

Just in case someone later doesn't wrap the use of it in a lock statement

used2could
That creates a separate copy of the lock for every thread, the net result of which will be no actual locking at all.
Aaronaught
-1, locking on a value of thread-static field is useless
Denis Krjuchkov
@Denis, I wasn't saying to add [ThreadStatic] if he already was using lock. i was using it as an alternative. He's using this static variable in a non-static function. In this situation i'm saying "lock" is acceptable or [ThreadStatic]. We don't know what else is happening in his code.
used2could