views:

52

answers:

2

Hi everyone,

I have implemented ReaderWriterLockSlim, Now i don't want it to wait at the lock. I want to do something else if the lock is held.

I considered using is isWriterLockHeld but it does not makes much sense to me, Since if two threads come in at the same time and enter the if statement at the same time one will still be waiting at the lock

here is my code.

ReaderWriterLockSlim rw = GetLoadingLock(parameters);
rw = GetLoadingLock(parameters);
try
{
  rw.EnterWriteLock();
  item = this.retrieveCacheItem(parameters.ToString(), false);
  if (item != null)
  {
      parameters.DataCameFromCache = true;

      // if the data was found in the cache, return it immediately
      return item.data;                              
  }
  else
  {
      try
      {
          object loaditem = null;
          itemsLoading[parameters.ToString()] = true;
          loaditem = this.retrieveDataFromStore(parameters);
          return loaditem;
      }
      finally {
         itemsLoading.Remove(parameters.ToString());
      }
  }
}
finally
{
  rw.ExitWriteLock();
}

Can anyone please guide me in the right direction with this.

Thanks

+1  A: 

Why don't you use TryEnterWriteLock() with a timeout TimeSpan of 0?

If timeout is 0 (zero), this method checks the lock state and returns false immediately if the desired state is unavailable.

Benjamin Podszun
+4  A: 

You can use the overload of TryEnterWriteLock() that takes a timeout as a parameter. If you pass it zero, it returns immediately if the lock could not be taken.

if(rw.TryEnterWriteLock(0))
{
    // do something with the lock held (don't forget to use a try/finally)
}
else
{
    // do something if the lock fails
}

On another matter, why are you assign rw twice?

ReaderWriterLockSlim rw = GetLoadingLock(parameters);
rw = GetLoadingLock(parameters); // This line is probably redundant

If you're using a Dictionary<string,bool> for itemsLoading, you can use an HashSet<string> instead.

Martinho Fernandes