This function will only throw an exception if some other thread besides the current thread currently owns the lock. The owning thread can re-acquire the lock as often as it wishes (but needs to match acquisition with Exit() calls). I don't think that's what you intended, is it?
Regards, Bob -----Original Message----- From: Moderated discussion of advanced .NET topics. [mailto:[EMAIL PROTECTED] Behalf Of John St. Clair Sent: Wednesday, April 02, 2003 2:35 PM To: [EMAIL PROTECTED] Subject: Re: [ADVANCED-DOTNET] Lock ownership static void AssertIsLocked(object o) { if (Monitor.TryEnter(o)) throw new ProgrammerNegligentException(); } Compiles in Outlook... John John St. Clair Prosjekt- og teamleder Reaktor AS -----Original Message----- From: Moderated discussion of advanced .NET topics. [mailto:[EMAIL PROTECTED] On Behalf Of Kamen Lilov Sent: 29. mars 2003 15:39 To: [EMAIL PROTECTED] Subject: [ADVANCED-DOTNET] Lock ownership I am trying to do something pretty simple and can't find a way to do it. Lets say I have objects that may be accessed from multiple threads. I synchronize access to them using the C# lock statement, equvalent to calling System.Threading.Monitor.Enter / Exit: public void SomeHighLevelMethod() { lock(this) { // .. do stuff .. SomePrivateMethod(); } To avoid code bloat and performance hits, I want to avoid using the lock statement in SomePrivateMethod; it _knows_ that when it is called, an object lock is already held by the current thread. To avoid bugs, however, in debug builds I'd like to have an assertion placed in every SomePrivateMethod that will abort the app if the method finds that its direct caller (or someone higher up the stack) has forgotten to obtain a lock. E.g. something like this: public class Utilities { [Conditional("DEBUG")] static bool AssertIsLocked(object obj) { if (!ObjectIsLockedByCurrentThread(obj)) throw new ProgrammerNegligentException(); // :)) } } I checked everywhere and couldn't find how to do this. Looks like System.Threading.Monitor supports only entering a crticial section (i.e. a lock), exiting it, and some sleep/pulse operations. I am fully aware that a method like ObjectIsLockedByCurrentThread() cannot be depended on for any kind of synchronization (I think understand multithreading); I need the above to work only for debugging purposes. Any ideas?
