Repository navigation
EN CSharp Async
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
async allows await within a method. await waits for the operation to complete and continues execution without necessarily creating a new thread. Task represents the completion of the operation, Task<T> represents the completion and result. An asynchronous method executes the synchronous part until the first pending wait.
Save this example separately as Example.cs. Run it independently of the other examples on this page.
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());Result:
7
async Task<int> CalculateAsync(int value)
{
await WaitAsync(10);
return value * 2;
}
int result = await CalculateAsync(21);
UO.Print(result.ToString());Task<int> FirstAsync() => Task.FromResult(2);
Task<int> SecondAsync() => Task.FromResult(3);
int[] results = await Task.WhenAll(FirstAsync(), SecondAsync());
UO.Print(results.Sum().ToString());Task.WhenAll waits for all tasks, WhenAny for the first completed one. Other tasks under WhenAny are not canceled automatically. ValueTask is useful in special API and has restrictions on re-waiting. Avoid .Wait() and .Result in an asynchronous chain; expect in await.
Official documentation: async, await, Task and ValueTask - Microsoft Learn.
ClassicUO — Bad Newbie & C# Scripts IDE