10

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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: Agreed, added a note in the answer. Thanks.
+1 for the "Yes you can...", -1 for the suggestion of locking on typeof(class), so an aggregate 0.
Maybe I've got some repressed, subconscious unicorn-jealousy going on!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.