我想我已经养成了一种货物崇拜的编程习惯:
每当我需要使类线程安全时,例如具有 Dictionary 或 List 的类(完全封装:从不直接访问并且仅由我的类的成员方法修改),我创建两个对象,如下所示:
public static class Recorder {
private static readonly Object _devicesLock = new Object();
private static readonly Dictionary<String,DeviceRecordings> _devices;
static Recorder() {
_devices = new Dictionary<String,DeviceRecordings>();
WaveInCapabilities[] devices = AudioManager.GetInDevices();
foreach(WaveInCapabilities device in devices) {
_devices.Add( device.ProductName, new DeviceRecordings( device.ProductName ) );
}
}//cctor
// For now, only support a single device.
public static DeviceRecordings GetRecordings(String deviceName) {
lock( _devicesLock ) {
if( !_devices.ContainsKey( deviceName ) ) {
return null;
}
return _devices[ deviceName ];
}
}//GetRecordings
}//class
在这种情况下,我将所有操作包装_devices
在一个lock( _devicesLock ) {
块中。我开始怀疑这是否有必要。为什么我不直接锁定字典?