c# - Volatile keyword usage vs lock

前端 未结 5 1218
予麋鹿
予麋鹿 2020-11-28 04:45

I\'ve used volatile where I\'m not sure it is necessary. I was pretty sure a lock would be overkill in my situation. Reading this thread (Eric Lippert comment) make me anxio

5条回答
  •  悲&欢浪女
    2020-11-28 05:14

    Volatile is woefully inadequate to make this code safe. You can use low-level locking with Interlocked.Increment() and Interlocked.CompareExchange() but there's very little reason to assume that Save() is thread-safe. It sure looks like it tries to save an object that's being modified by a worker thread.

    Using lock is very strongly indicated here, not just to protect the version numbers but also to prevent the object from changing while it is being serialized. The corrupted saves you'll get from not doing this are entirely too infrequent to ever have a shot a debugging the problem.

提交回复
热议问题