Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Task.WaitAsync: practical reference

Task.WaitAsync: practical reference: Task.WaitAsync adds timeout or cancellation to waiting without changing the original Task.

Version: .NET API; verified against .NET 10 reference surface

Syntax

Task.WaitAsync(/* overload-specific arguments */)

Task.WaitAsync adds timeout or cancellation to waiting without changing the original Task.

Use it to bound waiting time for an operation you do not control.

A timeout does not stop the underlying operation; its later result or failure must be handled separately.

An already completed Task may be returned without allocation; timeout throws TimeoutException.

The complete program actually uses Task.WaitAsync; its exact expected stdout is 12.

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;

var task = Task.FromResult(12);
Console.WriteLine(await task.WaitAsync(TimeSpan.FromSeconds(1)));

Result

12

The complete program actually uses `Task.WaitAsync`; its exact expected stdout is `12`.

Sources