开发者

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(), fa开发者_Go百科lse);
  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜