Skip to content

IT CSharp Keyword lock

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: lock

Manuale C# · Guida pratica

Esegue un blocco di mutua esclusione sull'oggetto specificato o su System.Threading.Lock. Non consente l'attesa in un blocco bloccato.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

Example.cs:

// PROJECT-EXAMPLE
var gate = new object();
int count = 0;
lock (gate) { count++; }
System.Console.WriteLine(count);

Risultato:

1

Sintassi

lock (gate) { ... }

Esempio 1: forma base

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        object gate = new(); int counter = 0;
        Parallel.For(0, 20, _ => { lock (gate) { counter++; } });
        Console.WriteLine(counter);
    }
}

Esempio 2: un'altra forma pratica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        System.Threading.Lock gate = new();
        List<int> values = [];
        Parallel.For(0, 10, i => { lock (gate) { values.Add(i); } });
        Console.WriteLine(values.Count);
    }
}

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally