C#挥发性双

编程入门 行业动态 更新时间:2024-10-27 19:19:34
本文介绍了C#挥发性双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

由于只有引用类型和一些原语(包括浮动,但不会增加一倍,我不知道为什么,我很高兴地听到,为什么的原因)可以被声明为挥发,如果我换了双一类那么声明为挥发性(如下图),将双重属性进行读写线程安全的,因为任何其他挥发性,或者我应该还是在看锁?

公共类MyThreadedClass {     挥发性VolatileDouble voldub; } 公共类VolatileDouble {     公共双人大床{获得;组; } }

解决方案

之所以双重不能声明挥发性:这是64位的,这使得它比基于x86字的大小,而起价地为p $ pvents它声明为volatile的CLI,如果我没记错的话。

以您目前的答案,只有引用的被视为是挥发性的。这意味着内存模型将确保它总是使用最新的参考,但它仍然使用过时的值。

我会用锁,如果我是你去,但有另一种方法是使用Interlocked.Read和 Interlocked.Exchange 作用于多头在与BitConverter.Int64BitsToDouble和BitConverter.DoubleToInt64Bits.你可以在 VolatileDouble 结构内封装这一点。 (我可能会使其成为一个结构,而不是一类。)

As only reference types and a few primitives (including float, but not double, I'm not sure the reason why, I'm happy to hear why) can be declared as volatile, if I wrap a double in a class then declare it as volatile (as below), will the double property be 'read write' thread safe as any other volatile, or should I still be looking at locking?

public class MyThreadedClass { volatile VolatileDouble voldub; } public class VolatileDouble { public double Double { get; set; } }

解决方案

Reason why double can't be declared volatile: it's 64 bits, which makes it more than the word size on x86, which prevents it from being declared volatile in the CLI if I remember correctly.

With your current answer, only the reference is treated as being volatile. That means the memory model will make sure it always uses the most recent reference, but it could still use a stale value.

I'd go with locking if I were you, but one alternative is to use Interlocked.Read and Interlocked.Exchange acting on longs, in conjunction with BitConverter.Int64BitsToDouble and BitConverter.DoubleToInt64Bits. You could encapsulate this within a VolatileDouble struct. (I'd probably make it a struct rather than a class.)

更多推荐

C#挥发性双

本文发布于:2023-05-27 19:05:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/299881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:挥发性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!