Saturday, November 10, 2012

How to lock a resource

List myList = new List();
public static ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();


public void myMethod(string Foo);
{
   myLock.EnterWriteLock(); //waits here if anything else has entered the lock
   myList.Add(Foo);
   myLock.ExitWriteLock();
}

public void myOtherMethod(string Bar);
{
   //Because this call doesn't use the lock, 
   //it ignores the lock and still can write to the list
   myList.Add(Bar);

   //this call would 'play nice' with other calls using the lock
   //once you use a lock on something, you should probably always
   //use a lock on that thing
   myLock.EnterWriteLock(); //waits here until the lock in myMethod is exited
   myList.Add(Bar);  
   myLock.ExitWriteLock();
}

No comments:

Post a Comment