You say you don't want to use lock
for performance reasons - but have you tested it?
(您说出于性能原因不想使用lock
-但是您已经测试过了吗?)
An uncontested lock (which this is likely to be, by the sounds of it) is pretty cheap. (毫无争议的锁(听起来很可能是这样)非常便宜。)
I generally go for "obviously correct" rather than "clever and possibly better performing" when it comes to threading (and in general, but especially for threading).
(在线程方面,我通常选择“明显正确”,而不是“聪明并且可能表现更好”(通常,尤其是对于线程)。)
Benchmark your app with and without locking, and see whether you can even notice the difference.
(使用和不使用锁定对您的应用程序进行基准测试,看看您是否还能注意到其中的区别。)
If locking makes a significant difference then sure, use cunning stuff. (如果锁定有很大的不同,那么请确保使用狡猾的东西。)
Otherwise, I'd just stick with a lock. (否则,我只会坚持锁。)
One thing you might want to do is use Interlocked.Increment
with an int
and just cast it when necessary to get a uint
, like this:
(您可能想做的一件事是将Interlocked.Increment
与int
配合使用,并在需要时将其uint
转换为uint
,例如:)
using System;
using System.Reflection;
using System.Threading;
public class Test
{
private static int count = int.MaxValue-1;
public static uint IncrementCount()
{
int newValue = Interlocked.Increment(ref count);
return unchecked((uint) newValue);
}
public static void Main()
{
Console.WriteLine(IncrementCount());
Console.WriteLine(IncrementCount());
Console.WriteLine(IncrementCount());
}
}
Output:
(输出:)
2147483647
2147483648
2147483649
(In other words it wraps with no problems.)
((换句话说,它包装起来没有问题。))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…