Another specific example:
class Program { public class Test { public string DoThis() { lock (this) { return "got it!"; } } } public delegate string Something(); static void Main(string[] args) { var test = new Test(); Something call = test.DoThis;
In this example, the first call will succeed, but if you track in the debugger, the DoSomething call will block until the lock is released. The second call will be blocked, since the main thread holds the monitor lock on the test .
The problem is that Main can block the instance of the object, which means that it can force the instance to do something that the object considers synchronized. The fact is that the object itself knows that it requires blocking, and external intervention just requires trouble. This is why the pattern of having a private member variable that you can use exclusively for synchronization without worrying about external interference.
The same goes for the equivalent static pattern:
class Program { public static class Test { public static string DoThis() { lock (typeof(Test)) { return "got it!"; } } } public delegate string Something(); static void Main(string[] args) { Something call =Test.DoThis;
Use a private static object for synchronization, not a type.
Darren Clark Apr 08 '09 at 8:02 2009-04-08 08:02
source share