C# - volatile

来源:互联网 发布:java会被淘汰吗 编辑:程序博客网 时间:2024/06/05 16:08
The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declaredvolatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

The volatile keyword can be applied to fields of these types:

  • Reference types.

  • Pointer types (in an unsafe context). Note that although the pointer itself can bevolatile, the object that it points to cannot. In other words, you cannot declare a "pointer tovolatile."

  • Types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.

  • An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.

  • Generic type parameters known to be reference types.

  • IntPtr and UIntPtr.

The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declaredvolatile.

4 1
原创粉丝点击