interlocked

Volatile vs. Interlocked vs. lock

家住魔仙堡 提交于 2019-11-25 22:45:25
问题 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 removing many lock statements and the use of Interlocked . But is there a reason not to do this? 回答1: Worst