Volatile vs. Interlocked vs. lock

Let’s say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, which approach should be used, and why? lock(this.locker) this.counter++;, Interlocked.Increment(ref this.counter);, Change the access modifier of counter to public volatile. Now that I’ve discovered volatile, I’ve been … Read more

Optimistic vs. Pessimistic locking

I understand the differences between optimistic and pessimistic locking. Now could someone explain to me when I would use either one in general? And does the answer to this question change depending on whether or not I’m using a stored procedure to perform the query? But just to check, optimistic means “don’t lock the table … Read more