私はカーゴカルトプログラミングの習慣を身につけたと思います:
Dictionary または List を持つクラス (完全にカプセル化されている: 直接アクセスされることはなく、クラスのメンバー メソッドによってのみ変更される) など、クラスをスレッドセーフにする必要があるときはいつでも、次のように 2 つのオブジェクトを作成します。
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 ) {
これが必要かどうか疑問に思い始めています。辞書を直接ロックしないのはなぜですか?