Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.IAsyncDisposable: practical reference

System.IAsyncDisposable: practical reference: IAsyncDisposable releases a resource through the ValueTask returned by DisposeAsync and the await using pattern.

Version: .NET API; verified on .NET 10.0.14

Syntax

System.IAsyncDisposable /* select a documented member or constructor */

IAsyncDisposable releases a resource through the ValueTask returned by DisposeAsync and the await using pattern.

Use it when cleanup itself requires asynchronous I/O or waiting.

Always await completion and do not use the resource afterward; a ValueTask normally must not be awaited repeatedly.

DisposeAsync can throw, and a partially constructed resource still needs a safe cleanup path.

The complete program actually uses System.IAsyncDisposable; its exact expected stdout is used\ndisposed.

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;

await using IAsyncDisposable resource = new AsyncResource();
Console.WriteLine("used");

sealed class AsyncResource : IAsyncDisposable { public ValueTask DisposeAsync() { Console.WriteLine("disposed"); return ValueTask.CompletedTask; } }

Result

used
disposed

The complete program actually uses `System.IAsyncDisposable`; its exact expected stdout is `used\ndisposed`.

Sources