Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

lock: practical reference

lock: practical reference: lock provides mutual exclusion on an object for the duration of its block.

Version: C# language; verified against C# 14 reference

Syntax

lock /* grammar-specific form */

lock provides mutual exclusion on an object for the duration of its block.

Use it for short protection of a shared synchronous invariant.

Do not lock this, a string, or a public object, and do not await inside lock.

An exception releases the lock, but inconsistent ordering of several locks causes deadlock.

The complete program actually uses lock; its exact expected stdout is locked.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var gate = new object(); lock (gate) { Console.WriteLine("locked"); }

Result

locked

The complete program actually uses `lock`; its exact expected stdout is `locked`.

Sources