次の方法で共有


volatile (C# Reference) 

The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile 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 (C# Reference) statement to serialize access. See How to: Create and Terminate Threads (C# Programming Guide) for an example of volatile in a multi-threaded scenario.

The volatile keyword can be applied to these types:

  • Reference types.

  • Pointer types (in an unsafe context).

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

  • An enum type with an integral base type.

  • Generic type parameters known to be reference types.

  • IntPtr and UIntPtr.

The type in question must be the field of a class or struct. Local variables cannot be declared volatile.

Example

The following sample shows how to declare a public field variable as volatile.

// csharp_volatile.cs
// compile with: /target:library
class Test
{
   public volatile int i;

   Test(int _i)
   {
      i = _i;
   }
}

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 3.10 Execution order

  • 10.4.3 Volatile fields

See Also

Reference

C# Keywords
Modifiers (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference