C# async, await and Task
Return a Task from an operation and observe its completion before printing success.
How it works
A Task represents an operation that may complete later, while Task<T> can also carry a result. await lets an async method suspend until completion without requiring a blocked caller thread for that wait. The async keyword does not automatically move CPU work to another thread. I/O-bound APIs often already provide asynchronous methods; CPU-heavy work needs its own scheduling and resource policy. Keep asynchronous operations observable so failures reach a caller instead of disappearing in fire-and-forget work.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
using System.Threading.Tasks;
internal static class Program
{
private static async System.Threading.Tasks.Task Main(string[] args)
{
int places = await AvailableAsync();
Console.WriteLine($"Available: {places}");
}
internal static async Task<int> AvailableAsync()
{
await Task.Yield();
return 8;
}
}
Expected result
Available: 8
Task.Yield creates a genuine asynchronous continuation boundary for this fixture, but it is not a simulated database call or a recommendation to add delay to ordinary calculations. The caller awaits before writing the result. In normal application code, avoid async void except for required event-handler signatures because its completion and exception handling are harder for callers to coordinate.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.