A nice site on .NET threading

 
BTW:  ReaderWriterLockSlim  rocks, especially when wrapped with IDisposable and usings: http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx
 
 

public static class Locks

{

public static void GetReadLock(ref ReaderWriterLockSlim locks)

{

bool lockAcquired = false;

while (!lockAcquired)

lockAcquired = locks.TryEnterUpgradeableReadLock(1);
}
 

public static void GetWriteLock(ref ReaderWriterLockSlim locks)

{

bool lockAcquired = false;

while (!lockAcquired)

lockAcquired = locks.TryEnterWriteLock(1);
}
 

public static void ReleaseReadLock(ref ReaderWriterLockSlim locks)

{

if (locks.IsUpgradeableReadLockHeld)

locks.ExitUpgradeableReadLock();
}
 

public static void ReleaseWriteLock(ref ReaderWriterLockSlim locks)

{

if (locks.IsWriteLockHeld)

locks.ExitWriteLock();
}
 

public static void ReleaseLock(ref ReaderWriterLockSlim locks)

{
ReleaseWriteLock(

ref locks);

ReleaseReadLock(

ref locks);

}
 

public static ReaderWriterLockSlim GetLockInstance()

{

return new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

}
}

public abstract class ObjectLock : IDisposable

{

protected ReaderWriterLockSlim _Locks;

public ObjectLock(ReaderWriterLockSlim locks)

{
_Locks = locks;
}

public abstract void Dispose();

}

public class ReadLock : ObjectLock

{

public ReadLock(ReaderWriterLockSlim locks) : base(locks)

{

Locks.GetReadLock(ref this._Locks);

}
 

public override void Dispose()

{

Locks.ReleaseReadLock(ref this._Locks);

}
}

public class WriteLock : ObjectLock

{

public WriteLock(ReaderWriterLockSlim locks) : base(locks)

{

Locks.GetWriteLock(ref this._Locks);

}
 

public override void Dispose()

{

Locks.ReleaseWriteLock(ref this._Locks);

}
}

 
 
Use this like:
 
static ReaderWriterLockSlim myLockForResource = Locks.GetLockInstance();
 

using (new ReadLock(_myLockForResource))

{
//do stuff
}

 
There may be a little danger in this, although the comments seem from beta; see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=305001

 

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to A nice site on .NET threading

  1. BrianR says:

    I posted a simple update to this code, which should eliminate some of the lock upgrade issues.
     
    Check it out:
    http://devplanet.com/blogs/brianr/archive/2008/09/29/thread-safe-dictionary-update.aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s