I recently came across this very interesting bug. Note: the problem requires understanding of threads, generics, inheritance and locks.
In particular look at the Locking Bug code. Specifically, notice how the locking behaviour changes based on the types used for the generic base class.
- When the types are same, the base class object used for locking is the same.
- So locking can be enforced by doing something like
- private static readonly object Padlock = new object();
- lock (Padlock)
- So locking can be enforced by doing something like
- However, when the types are different, the compiler creates two completely different memory objects, hence the locking does not come into play
- A possible solution is to create a separate internal class and enforce locking using the typeof that class
- internal class ForLocking {}
- lock (typeof(ForLocking))
- If you dont prefer using typeof, another option is to create a separate class and have a static lockObject in it.
- See code.
- http://stackoverflow.com/questions/8185004/lockx-vs-locktypeofx
- A possible solution is to create a separate internal class and enforce locking using the typeof that class
Code:
References: