问题
The Interlocked.CompareExchange()
method (docs) does roughly speaking this:
"I have a variable, and I think I know what value it currently has. If I'm right, then please change the value to that".
The point being that this method can be used to safely update a variable in a multi-threaded context. If the value has changed since the caller thought it knew what the value was, then some other thread has made that change, so this thread needs to retry (or whatever other behaviour is appropriate)
The return value of Interlocked.CompareExchange()
is "the original value of the variable".
i.e. the actual value of the variable we thought we knew the value of, at the point of invocation.
That seems ... weird.
It seems clear to me that almost every invocation of this method is then going to be followed by comparing the return value with the previously believed value. i.e. you want to know whether you won the race to update the value. So the "conversation" goes.
- "I have a variable, which I think has value X. If I'm right, please set it to Y."
- Then
CompareExchange()
says "The variable had value Z when you asked me", which I then compare to my earlier X to I infer whether or not I won.
Why doesn't CompareExchange()
just return a boolean
success flag? (Much like TryParse()
et. al.)
The value of the variable at the point of invocation isn't going to be useful barring some very obscure cirumstances, because the value you have immediate goes out of date; other threads could have updated the variable after the return value was received.
Why return that value, rather than the more obviously useful boolean?
来源:https://stackoverflow.com/questions/59388171/is-there-some-good-reason-for-the-return-value-of-interlocked-compareexchange