如何以线程安全的方式增加(添加值)十进制?

问题描述:

我有一个可同时从多个线程访问的 decimal 变量.Interlocked 类函数根本不支持小数,所以我剩下的唯一方法是使用 lock(){}.这似乎有点矫枉过正.

I have a decimal variable that is accessed from multiple threads at the same time. Interlocked class functions do not support decimals at all, so the only approach I'm left with is using lock(){}. It seems to be an overkill.

是否有其他方法以线程安全的方式为 decimal 变量添加值?

It there some other way to add value to decimal variable in a thread-safe way?

使用锁并不过分.它是必需的.

Using lock is not overkill. It is required.

像 System.Decimal 这样的结构类型从来都不是原子的,它也不适合原生 cpu 字长.这就是 Interlocked 也没有过载的原因.

Structure types like System.Decimal are never atomic, it also doesn't fit the native cpu word size. Which is why Interlocked doesn't have an overload for it either.