Home  >  Article  >  Backend Development  >  volatile keyword in C#

volatile keyword in C#

PHPz
PHPzforward
2023-08-26 19:05:05771browse

C# 中的 volatile 关键字

To reduce concurrency issues in C#, use the volatile keyword. Let's look at an example.

Here's how to use volatile keyword for public variables -

class Program {
   public volatile int a;
   public void Program(int _a) {
      i = _i;
   }
}

Let's see another example: We have two static variables. Set them as new methods -

_out = "Welcome!";
_new = true;

We declared them as static before using volatile -

static string _out;
static volatile bool new;

Now you need to run the method on a thread -

new Thread(new ThreadStart(volatileFunc)).Start();

Read Get the value of a volatile variable-

if (_new) {
   Console.WriteLine(_out);
}

The above is the detailed content of volatile keyword in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete