[RESOLVED]static variables must be volatile or not

If I use this variable from controller I need to create it with volatile keyword?

No – unless you need it. Why do you think you need volatile?

static and volatile are for different purposes

1. Static  : Is shared state between all instances of a class

2. volatile: Is access to be shared between multiple threads

3. Yes if this field is to be shared for all instances and and to be accessed by multiple threads, you can use static and volatile

Hi Alex9,

Thanks for your post.

According to your description,

Alex9

If I use this variable from controller I need to create it with volatile keyword?

No.

The volatile keyword is a convenience keyword  for those who need to access member variables of a class or structure in  multi-threaded conditions.

The purpose of the volatile keyword is to tell  the compiler that the variable you are marking as volatile may be accessed by  multiple threads. There are certain optimizations that
the csharp compiler makes  when it compiles our code and unless the variable is marked as volatile, the  compiler will make optimizations assuming that the variable will only be  accessed by one thread at a time.

More information:

#Volatile keyword in C# Threading

http://www.c-sharpcorner.com/UploadFile/1d42da/volatile-keyword-in-C-Sharp-threading/

Hope this can be helpful.

Best Regards,

Eileen

Leave a Reply