Is there a neat way to do this using the Interlocked class? Or should I just use lock { }?
My specific use case is that I have multiple threads that compute a long value, and compare it to a shared “Maximum” value, replacing the shared value only if the local value is larger.
Try the
Interlocked.CompareExchangemethod. I haven’t tried, but something like this seems logical to me:As usual, stress test your code to try to catch concurrency issues.