I have been reading the docs on Threading Design Guidelines for Class Library Developers and I ran across the following section I just don't follow. Here is the first part of it:
Be aware of issues with the lock statement (SyncLock in Visual Basic). It is tempting to use the lock statement to solve all threading problems. However, the System.Threading.Interlocked Class is superior for updates that must be made automatically. It executes a single lock prefix if there is no contention. In a code review, you should watch out for instances like the one shown in the following example. lock(this) { myField++; } So I was expecting the docs to recommend doing something like this instead: Interlocked.Increment(myField); Instead, it goes on to say this (the second part): Alternatively, it might be better to use more elaborate code to create rhs outside of the lock, as in the following example. Then, you can use an interlocked compare exchange to update x only if it is still null. This assumes that creation of duplicate rhs values does not cause negative side effects. if (x == null) { lock (this) { if (x == null) { // Perform some elaborate code to create rhs. x = rhs; } } } I don't follow the code above. Can anybody shed some light on this guideline. -- Keith You can read messages from the DOTNET archive, unsubscribe from DOTNET, or subscribe to other DevelopMentor lists at http://discuss.develop.com.