System.Threading

Lock Struct

Represents a lightweight synchronization primitive that can be used for mutual exclusion. It is a value type and is typically used within a lock statement in C#.

On this page

Introduction

The Lock struct is a fundamental part of C#'s concurrency model, providing a simple and efficient way to protect shared resources from concurrent access by multiple threads. It is the underlying mechanism for the lock statement, which simplifies the process of acquiring and releasing synchronization primitives.

Syntax

public struct Lock

Remarks

The Lock struct is not intended to be instantiated directly by the user. Instead, it is used implicitly by the C# compiler when you use the lock statement:

private readonly object _lockObject = new object();

void AccessSharedResource()
{
    lock (_lockObject)
    {
        // Critical section: Code that accesses shared resources.
        // Only one thread can execute this code at a time.
        Console.WriteLine("Accessing shared resource...");
    }
}

When the compiler encounters a lock statement, it transforms it into code that uses the underlying synchronization primitives, effectively acquiring a lock before entering the code block and releasing it upon exiting, even if exceptions occur.

Constructors

The Lock struct does not have any public constructors. It is managed internally by the C# runtime and the compiler.

Methods

The Lock struct does not expose any public methods directly to the developer.

Members

The Lock struct, when used via the lock statement, relies on the object provided as the lock token. This token must be a reference type. Common choices include a dedicated object instance or this for instance-level locking.

Member Description
lock (expression) { statement_block } The C# lock statement. Acquires a mutual-exclusion lock for the duration of the statement_block. The expression must evaluate to a reference type object.