Volatile keyword in C #

Source: Internet
Author: User

volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. the volatile keyword indicates that a field can be modified by multiple concurrent threads. volatile are not subject to compiler optimizations that assume access by a single thread. "> fields declared as volatile are not restricted by Compiler Optimization (assuming that they are accessed by a single thread. this ensures that the field displays the latest value at any time.

VolatileModifiers are usually used for fields accessed by multiple threads but not serialized by using the lock statement.

VolatileKeywords can be applied to the following types of fields:

  • Reference type.

  • Pointer type (in an insecure context ).Note that although the pointer itself can be variable, the object it points to cannot be variable.In other words, you cannot declare a pointer to a mutable object ".

  • Type, such as sbyte, byte, short, ushort, Int, uint, Char, float, and bool.

  • An Enumeration type that has one of the following basic types: byte, sbyte, short, ushort, Int, or uint.

  • It is known that it is a generic parameter of the reference type.

  • IntptrAndUintptr.

Variable keywords can only be applied to class or structure fields.You cannot declare a local variableVolatile.

Example

The following example shows how to declare a public field variableVolatile.

C # copy
  class  volatiletest { Public   volatile   int  I;  Public   void  test ( int  _ I) {I = _ I ;}

The following example shows how to create a secondary thread and use it to execute processing in parallel with the main thread.For background information about multithreading, seeManaged thread processingAndThread processing (C # and Visual Basic).

C # copy
 Using System; Using System. Threading; Public  Class Worker { // This method is called when the thread is started.      Public   Void Dowork (){ While (! _ Shouldstop) {console. writeline ( "Worker thread: working ..." );} Console. writeline ( "Worker thread: Terminating gracefully ." );} Public   Void Requeststop () {_ shouldstop = True ;}// Keyword volatile is used as a hint to the compiler that this data      // Member is accessed by multiple threads.      Private   Volatile   Bool _ Shouldstop ;} Public   Class Workerthreadexample { Static   Void Main (){ // Create the worker thread object. This does not start the thread. Worker workerobject = New Worker (); thread workerthread =New Thread (workerobject. dowork ); // Start the worker thread. Workerthread. Start (); console. writeline ( "Main thread: starting worker thread ..." ); // Loop until the worker thread activates.          While (! Workerthread. isalive ); // Put the main thread to sleep for 1 millisecond          // Allow the worker thread to do some work. Thread. Sleep (1 ); // Request that the worker thread stop itself. Workerobject. requeststop ();// Use the thread. Join method to block the current thread          // Until the object's thread terminates. Workerthread. Join (); console. writeline ( "Main thread: worker thread has terminated ." );} // Sample output:      // Main thread: starting worker thread...      // Worker thread: working...      // Worker thread: working...      // Worker thread: working...      // Worker thread: working...      // Worker thread: working...      // Worker thread: working...     // Worker thread: Terminating gracefully.      // Main thread: worker thread has terminated. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.