SoFunction
Updated on 2025-03-06

Usage of volatile and lock in C#

This article describes the usage of volatile and lock in C# and is shared with you for your reference. The specific analysis is as follows:

1. volatile in C#

volatile is a keyword used in C# to control synchronization. Its meaning is to target some sensitive data in the program. Multiple threads are not allowed to access simultaneously, ensuring that the data has at most one thread at any access moment to ensure the integrity of the data. volatile is a modifier that modifies variables.

1. Use scenarios of volatile

Multiple threads access a variable at the same time. For efficiency, CLR allows each thread to cache locally, which leads to inconsistency in variables. volatile is to solve this problem. Variables modified by volatile do not allow threads to cache locally. Each thread's read and write is directly operated on shared memory, which ensures that the variables are always consistent.

2. The volatile keyword can be applied to the following types of fields

① Reference type

② Integer, such as sbyte, byte, short, ushort, int, uint, char, float and bool.

③ Enumeration type with integer base type.

④ Generic type parameters known as reference type.

⑤ Local variables cannot be declared as volatile.

2. Lock in C#

1. The lock keyword marks the statement block as a critical area by obtaining the mutex of the given object, executing the statement, and then releasing the lock. The form of this statement is as follows:

Copy the codeThe code is as follows:
Object thisLock = new Object();
lock (thisLock)
{
    // Critical code section
}

2. Lock ensures that when one thread is in the critical area of ​​the code, the other thread does not enter the critical area. If other threads try to enter the locked code, it is blocked until the object is released. That is to say, when using critical resources, it is a method that ensures that threads can queue up to enter the execution critical section.

3. Use scenarios of lock

Multiple threads access a code block at the same time, use lock to modify the code block, and force multiple threads to queue up and access one by one.

Generally, locking the public type should be avoided, otherwise the instance will be out of control of the code. The best practice is to define private objects to lock, or private static object variables to protect data shared by all instances.

I hope this article will be helpful to everyone's C# programming.