简体   繁体   中英

Do something else if ReadWriteSlimlock is held

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

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 assigning 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM