2

I'm trying to make things simpler. Here is my code:

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

This is even worse than the ReaderWriterLock in terms of noise. I can use C# or VB, so answers applying to either will be welcome.

TGamer
  • 529
  • 1
  • 9
  • 26
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447

2 Answers2

6

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
  • 10,324
  • 6
  • 55
  • 66
4

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.

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900