Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

async: practical reference

async: practical reference: async enables await; an async method may return void, Task, Task<T>, or a suitable task-like type such as ValueTask/ValueTask<T>, while an async iterator that produces a stream returns IAsyncEnumerable<T>.

Version: C# language and .NET 10 reference runtime

Syntax

async /* grammar-specific form */

async enables await; an async method may return void, Task, Task, or a suitable task-like type such as ValueTask/ValueTask, while an async iterator that produces a stream returns IAsyncEnumerable.

Use it for naturally asynchronous I/O and propagate the Task to the caller.

Restrict async void to event handlers; its exceptions cannot be awaited normally.

The method can finish synchronously until the first incomplete await.

The complete program actually uses async; its exact expected stdout is 5.

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;

Console.WriteLine(await ReadAsync());
static async Task<int> ReadAsync() { await Task.Yield(); return 5; }

Result

5

The complete program actually uses `async`; its exact expected stdout is `5`.

Sources