Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top