如何以线程安全的方式增加(添加值)十进制? [英] How to increment (add value to) decimal in a thread-safe way?

查看:23
本文介绍了如何以线程安全的方式增加(添加值)十进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可同时从多个线程访问的 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.

这篇关于如何以线程安全的方式增加(添加值)十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆