The double lock flag is what you need:
That's what you need:
class Foo { private object someLock = new object(); private object someFlag = false; void SomeMethod() {
In general, when you encounter similar problems, try and follow well-known patterns like the ones above. This makes it recognizable and less error prone, since you are less likely to miss something when you follow the pattern, especially when it comes to streaming.
In your case, the first, if it does not make much sense, but often you need to execute the actual logic, and then set the flag. The second thread will be blocked while you execute your (perhaps quite expensive) code.
About the second example:
Yes, that’s right, but don’t make it more complicated than that. You must have very good reasons not to use a simple lock, and in this situation it makes the code more complicated (since Interlocked.CompareExchange() less known) without achieving anything (because you indicated that the lock is less than the lock to set the Boolean flag on the in fact, it is not profitable).
ntziolis
source share