Partition is a small class I created. I have thousands of partitions that reside in a ConcurrentDictionary named Partitions. Before serialization, I want to lock a specific partition, do some work and then unlock the partition.
During this time no other threads should be able to access that Partition. Since my class Partition is a reference type, I am wondering if I can lock on a single Partition object as I have in the code below?
Will this block other threads from a single Partition in the ConcurrentDictionary Partitions during the lock below?
I don't want to lock using a class level locker object. My thought process is that multiple threads should be able to run the code below at the same time. They just should not be able to access a specific partition, if it is locked...
private void serializePartition(int partNo)
{
Partition p;
//Get a reference to the partition, lock, and save it to disk.
lock (p = Partitions[partNo])
{
using (var file = File.Create(dataPath + tableName + partNo + ".ppmi"))
{
Serializer.Serialize(file, p);
}
//decrement _CurrentRecordsInMemory by the size of the partition.
Interlocked.Add(ref _CurrentRecordsInMemory, p.Data.Count * -1);
//Clear the partitions data to free up memory and reset partition variables
p.Data = null;
p.OnDisk = true;
p.StartCount = 0;
}
}