CKTIS / C#
async: riferimento pratico
async: riferimento pratico: async abilita await; un metodo async può restituire void, Task, Task<T> o un tipo task-like adatto come ValueTask/ValueTask<T>, mentre un iteratore async che produce uno stream restituisce IAsyncEnumerable<T>.
Versione: C# language and .NET 10 reference runtime
Sintassi
async /* grammar-specific form */async abilita await; un metodo async può restituire void, Task, Task o un tipo task-like adatto come ValueTask/ValueTask, mentre un iteratore async che produce uno stream restituisce IAsyncEnumerable.
Usalo per I/O naturalmente asincrono e propaga il Task al chiamante.
Limita async void agli event handlers; le sue eccezioni non possono essere attese normalmente.
Il metodo può terminare sincronicamente fino al primo await incompleto.
Il programma completo usa realmente async; lo stdout esatto atteso è 5.
Esempi
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;
Console.WriteLine(await ReadAsync());
static async Task<int> ReadAsync() { await Task.Yield(); return 5; }
Risultato
5
Il programma completo usa realmente `async`; lo stdout esatto atteso è `5`.