I think I developed a habit of culinary cult:
Whenever I need to make a class thread safe, for example a class that has a dictionary or list (which is fully encapsulated: it has never been accessed directly and changed only by member methods of my class) I create two objects, for example:
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 ) ); } }
In this case, I complete all operations on _devices in the lock( _devicesLock ) { block. I begin to think, if necessary. Why don't I just lock the dictionary directly?
source share