Skip to content

IT CSharp Async

Codex edited this page Oct 11, 2026 · 2 revisions

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

asincrono, attendi, Attività è ValueTask

Manuale C# · Esempi UO

async consente await all'interno di un metodo. await attende il completamento dell'operazione e ne prosegue l'esecuzione senza necessariamente creare un nuovo thread. Task rappresenta il completamento dell'operazione, Task<T> rappresenta il completamento e il risultato. Un metodo asincrono esegue la parte sincrona fino alla prima attesa pendente.

Esempio semplice (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
async System.Threading.Tasks.Task<int> ReadAsync()
{
    await System.Threading.Tasks.Task.Delay(1);
    return 7;
}
System.Console.WriteLine(await ReadAsync());

Risultato:

7
async Task<int> CalculateAsync(int value)
{
    await WaitAsync(10);
    return value * 2;
}
int result = await CalculateAsync(21);
UO.Print(result.ToString());
Task<int> FirstAsync() => Task.FromResult(2);
Task<int> SecondAsync() => Task.FromResult(3);
int[] results = await Task.WhenAll(FirstAsync(), SecondAsync());
UO.Print(results.Sum().ToString());

Task.WhenAll attende tutte le attività, WhenAny la prima completata. Le altre attività in WhenAny non vengono annullate automaticamente. ValueTask è utile in speciale API e presenta restrizioni sulla riattesa. Evitare .Wait() e .Result in una catena asincrona; aspettatevi in ​​await.

Documentazione ufficiale: asincrono, attendono, Attività e ValueTask - Microsoft Learn.

Clone this wiki locally