如果您发现任何性能改进,错误或任何您要更改的内容以及原因,请与我们联系。
public static bool TrySpeculativeUpdate(ref int field, out int result,
Func<int, int> update, Func<int, bool> shouldAbort)
{
SpinWait spinWait = new SpinWait();
while (true)
{
int snapshot = field;
if (shouldAbort(field))
{
result = 0;
return false;
}
else
{
int calc = update(snapshot);
if (Interlocked.CompareExchange(ref field, calc, snapshot) == snapshot)
{
result = calc;
return true;
}
}
spinWait.SpinOnce();
}
}
可以像这样使用
private bool TryIncreaseCapacity(out int newCapacity)
{
return TrySpeculativeUpdate(ref _currentCapacity, out newCapacity,
(currentCapacity) => currentCapacity + 1,
(currentCapacity) => currentCapacity == _maxCapacity);
}
if (this.TryIncreaseCapacity(out newCapacity))
{
...
}
else
{
...
}
我真正想要完成的是Interlocked.Increment的最快线程安全版本,它将停止以最大值递增,并且我将有一些检测它停止递增的方法。