Is it safe to lock a static variable in a non-static class?
- by Dario Solera
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?