"Interlocked Example"

private static void AThreadStart() {
	while (true) {
		lock (lockObj) {
			if (counter < COUNTER_TARGET) counter++;
			else break;
		}
	}
}

private static void BThreadStart() {
	int prevValue = counter;
	while (prevValue < COUNTER_TARGET) {
		Interlocked.CompareExchange(ref counter, prevValue + 1, prevValue);
		prevValue = counter;
	}
}


Code snippet taken from "Common Multithreading Mistakes in C# - II: Unnecessary Contention".