Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / C#

async: référence pratique

async: référence pratique: async permet await ; une méthode async peut renvoyer void, Task, Task<T> ou un type task-like approprié tel que ValueTask/ValueTask<T>, tandis qu’un itérateur async produisant un flux renvoie IAsyncEnumerable<T>.

Version : C# language and .NET 10 reference runtime

Syntaxe

async /* grammar-specific form */

async permet await ; une méthode async peut renvoyer void, Task, Task ou un type task-like approprié tel que ValueTask/ValueTask, tandis qu’un itérateur async produisant un flux renvoie IAsyncEnumerable.

À utiliser pour des I/O naturellement asynchrones en propageant le Task à l’appelant.

Limitez async void aux event handlers ; ses exceptions ne peuvent être attendues normalement.

La méthode peut finir synchroniquement jusqu’au premier await incomplet.

Le programme complet utilise réellement async ; sa sortie stdout exacte attendue est 5.

Exemples

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; }

Résultat

5

Le programme complet utilise réellement `async` ; sa sortie stdout exacte attendue est `5`.

Sources