Skip to content

ZH TW CSharp Keyword async

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: async

使用手冊C# · 實用指南

在可調用成員中啟用等待。此方法可以傳回一個 Task、Task、ValueTask 或非同步序列; async 本身並不會啟動單獨的執行緒。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
async System.Threading.Tasks.Task<int> ReadAsync()
{
    await System.Threading.Tasks.Task.Delay(1);
    return 7;
}
System.Console.WriteLine(await ReadAsync());

結果:

7

句法

async Task MethodAsync() { await ...; }

例1:基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        int result = await Jobs.DoubleAsync(4);
        Console.WriteLine(result);
    }
}
public static class Jobs { public static async Task<int> DoubleAsync(int value) { await Task.Delay(1); return value * 2; } }

例2:另一種實用形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Task<int>[] jobs = [Jobs.CountAsync(2), Jobs.CountAsync(3)];
        int[] results = await Task.WhenAll(jobs);
        Console.WriteLine(results.Sum());
    }
}
public static class Jobs { public static async Task<int> CountAsync(int value) { await Task.Yield(); return value; } }

官方來源:Microsoft學習。

Clone this wiki locally