I want to use an Interlocked.Add
method because it's faster for int
and long
. I have following code for others types:
short x = Sum(source, range.Item1, range.Item2);
checked
{
lock (syncRoot)
result += x;
}
But I found that Interlocked doesn't handle overflows. How can I determine that overflow or underflow occured? x
can be either positive or negative.
var x = Sum(source, range.Item1, range.Item2);
Interlocked.Add(ref result, x);
bool overflow = ...
if (overflow)
throw new OverflowException();
I found following tip on MSDN but don't know how can I implement this check:
This method handles an overflow condition by wrapping: if the value at location1 is Int32.MaxValue and value is 1, the result is Int32.MinValue; if value is 2, the result is (Int32.MinValue + 1); and so on.No exception is thrown.