views:

49

answers:

2

I'm creating an ASP.net website which handles thousands of requests and it all stems from one main object that they all share to read it. I'm trying to wrap my head around these different types of locks.

Some common questions i have for each.

  1. What is the scope of each lock Application, Session,Object
  2. When is it right to use one over the other?
  3. Can multiple users run the code in the lock at one time?
  4. Performance Hit?

1.

public class MyClass
   {
      lock
      {
        // DO COOL CODE STUFF.
      }
   }

2.

public class MyClass
{
  Application.Lock  
  // DO COOL CODE STUFF.
  Application.Unlock 
 }

3.

public static object lockObject = new object();
public class MyClass
{    
    lock(lockObject) 
    {
      // DO COOL CODE STUFF. 
    }
}

4.

private static readonly ReaderWriterLockSlim slimLock =  new ReaderWriterLockSlim();
public class MyClass
{
    slimLock.EnterWriteLock();
    // DO COOL CODE STUFF HERE.     
    slimLock.ExitWriteLock();
}
+1  A: 

Locking a single object will not scale very well. As an alternative, I would suggest considering the Object Pool design pattern. It is much more capable of growing to meet your increasing user demands.

James Jones
A: 

Read the docs for all these things:

1)

Application.Lock() and Application.Unlock()

The Lock method blocks other clients from modifying the variables stored in the Application object citation

2) You cannot do this:

public class MyClass
{
   lock
   {
     // DO COOL CODE STUFF.
   }
}

3) The ReaderWriterLockSlim should be used if you can have multiple clients reading at once, but write access has to have exclusive access.

4) This code:

public static object lockObject = new object();
public class MyClass
{    
    lock(lockObject) 
    {
      // DO COOL CODE STUFF. 
    }
}

will mean only 1 thread can be within that block at a time. Meaning serialized read access.

tster