I've been given an assignment to write a max counter class with the following contract:
class MaxCounter
{
private int _value = int.MinValue;
public void Max(int value)
{
if(value > _value)
{
_value = value;
}
}
public int Value => _value;
}
The assignment asked to implement a thread-safe, non-locking solution using the Interlocked
class. I thought about this implementation:
public void Update(int value)
{
if (value > Interlocked.Read(ref _value))
{
Interlocked.Exchange(ref _value, value);
Console.WriteLine("Thread {0} updated counter to {1}.", Thread.CurrentThread.ManagedThreadId, value);
}
}
But I believe it can be improved with the CompareExchange
function. What do you think?