分区是我创建的一个小类。我有数千个分区驻留在名为 Partitions 的 ConcurrentDictionary 中。在序列化之前,我想锁定一个特定的分区,做一些工作然后解锁分区。
在此期间,没有其他线程应该能够访问该分区。由于我的类 Partition 是一个引用类型,我想知道我是否可以像下面的代码中那样锁定单个 Partition 对象?
这会在下面的锁定期间阻塞来自 ConcurrentDictionary 分区中的单个分区的其他线程吗?
我不想使用类级别的储物柜对象进行锁定。我的思考过程是多个线程应该能够同时运行下面的代码。他们只是不应该能够访问特定的分区,如果它被锁定......
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;
}
}