Original code:
var can = rateLock.WaitAsync();
if (can.IsCompletedSuccessfully) // for safety but do I need it?
{
if (!increase)
{
errorRate = (byte)(errorRate - Convert.ToByte(errorRate > 0));
}
else
{
errorRate++;
}
if (errorRate > 50)
{
TimerStop(true);
}
rateLock.Release();
}
Modified to:
if (increase)
{
if (Interlocked.Increment(ref errorRate) > 50)
{
TimerStop(true);
}
}
else
{
Interlocked.Exchange(ref errorRate, (errorRate - Convert.ToInt32(errorRate > 0)));
}
The problem: As you can see, the "decrementing" part relies on the same variable value that needs to be read twice, then boolean and substraction operations performed and all of this outside of Interlocked context.
I really liked possibility of having no extra SempahoreSlim (async env) - is there any way to make decrementing work with custom condition avoiding tons of IFs (I need to keep errorRate >=0)?