什么是“动荡”关键字在C#中的目的 [英] What is the purpose of 'volatile' keyword in C#

查看:124
本文介绍了什么是“动荡”关键字在C#中的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是挥发性关键字在C#中的目的是什么?



我在哪里需要使用此关键字?



我看到了下面的语句,但我无法理解为什么挥发性这里需要?

 内部动荡字符串用户名; 


解决方案

我是指你的规范的第10.5.3 ,其中规定:




有关非易失性领域,优化
技术,指令重新排序,
可能会导致意外和
不可预知的结果在访问
领域不同步,如
,通过锁定声明
(§8.12)提供的
多线程程序。这些优化可以是由编译器执行
,由
运行时系统,或由硬件。对于
挥发性领域,如重新排序
优化受到限制:



volatile字段的
读称为
挥发性读取。挥发性读了
获取语义;也就是说,它是保证发生内存
它在指令序列之后出现的任何
引用之前



一个$ B挥发性场$ B写入称为
性写。挥发性写有
释放语义;也就是说,它是保证之前在指令
基因序列的写入
指令任何存储器
的引用之后发生



这些限制确保
所有线程将观察挥发性
写入由任何其他线程
在它们为$顺序执行b $ b用。是不是需要一个符合标准的实现
提供挥发性写入从执行的所有线程看到

总排序。




阅读极其认真的如果你曾经使挥发性场的打算。如果不这样做的完全彻底地的理解挥发性语义的所有影响,那么请不要尝试使用它们。它通常是更好的使用锁,它会自动给你足够的内存屏障,以确保必要的获取和释放语义。请记住,锁是当他们只争真的很贵。


What is the purpose of volatile keyword in C#?

Where would I need to use this keyword?

I saw the following statement, but I am unable to understand why volatile is required here?

internal volatile string UserName; 

解决方案

I refer you to section 10.5.3 of the specification, which states:

For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multi-threaded programs that access fields without synchronization such as that provided by the lock-statement (§8.12). These optimizations can be performed by the compiler, by the run-time system, or by hardware. For volatile fields, such reordering optimizations are restricted:

A read of a volatile field is called a volatile read. A volatile read has "acquire semantics"; that is, it is guaranteed to occur prior to any references to memory that occur after it in the instruction sequence.

A write of a volatile field is called a volatile write. A volatile write has "release semantics"; that is, it is guaranteed to happen after any memory references prior to the write instruction in the instruction sequence.

These restrictions ensure that all threads will observe volatile writes performed by any other thread in the order in which they were performed. A conforming implementation is not required to provide a single total ordering of volatile writes as seen from all threads of execution.

Read that extremely carefully if you have any intention of ever making a volatile field. If you do not completely and thoroughly understand all the implications of volatile semantics then do not attempt to use them. It is usually far better to use a lock, which automatically gives you sufficient memory barriers to ensure the necessary acquire and release semantics. Remember, locks are only really expensive when they are contended.

这篇关于什么是“动荡”关键字在C#中的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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