First of all, in an ASP.NET application, you're better off using the HttpCache object, rather a simple static collection.
On to your actual question, you can indeed maintain a single lock for every item in your collection (every object has a monitor in .NET, so they are relatively cheap). However, you probably want to do this in tandem with having a lock for the actual collection:
I'll use static here for simplicity, but as I mentioned above, HttpCache might be better:
class CacheItem
{
private readonly object _lock = new object();
public void DoSomething()
{
lock(_lock)
{
// perform some synchronized action on the individual item
}
}
}
// I'd recommend a reader-writer lock for the
// collection so that you can have multiple retrievals
// of items and still lock exclusively for changing the collection
private static ReaderWriterLockSlim itemsLock = new ReaderWriterLockSlim();
private static List<CacheItem> items = new List<CacheItem>();
public static void AddItem(CacheItem item)
{
itemsLock.EnterWriteLock();
try
{
items.Add(item);
}
finally
{
itemsLock.ExitWriteLock();
}
}
pulbic static CacheItem GetItem(int index)
{
itemsLock.EnterReadLock();
try
{
return items[index];
}
finally
{
itemsLock.ExitReadLock();
}
}