views:

1326

answers:

2

This is even worse than the ReaderWriterLock in terms of noise.

 If Threading.Monitor.TryEnter(syncRoot) Then
  Try
   'do something
  Finally
   Threading.Monitor.Exit(syncRoot)
  End Try
 Else
  'do something else
 End If

Both C# and VB solutions are welcome.

+3  A: 

This is very similar to your last post, and I would expect a similar answer. The only significant difference is that you might return "null" from your method if the timeout fails - then the "Dispose()" is not called, and you can easily check the value:

using(var token = GetLock(syncLock, timeout)) {
  if(token != null) { ... }
}

The only real glitch is that you don't necessarily want to add an extension method to "object" (or even "T where T : class")...

Jon Skeet has looked at this in the past - worth a look.

Marc Gravell
Passing a possible null to the using block is a neat trick. But it still feels kludgey to me.
Jonathan Allen
(note I edited to make the timeout visible in the call)
Marc Gravell
+4  A: 

Use a delegate?

E.g.

public bool TryEnter(object lockObject, Action work) 
{
    if (Monitor.TryEnter(lockObject)) 
    {
       try 
       {
          work();
       }
       finally 
       {
           Monitor.Exit(lockObject);
       }        
       return true;
     }

     return false;
}
Richard Nienaber
Totally useless for VB (no anonymous Action delegates), but I can see it working with C#.Can you show how you foresee it being called?
Jonathan Allen
Simplest would be with a lambda: TryEnter(obj, ()=>{...code...})), where the return tells you whether it was done or not.
Marc Gravell
Now that VB 10 has anonymous delegates, this is my favorite solution.
Jonathan Allen