Programming languages · Advanced · 26 min
Write async code in C# with Task, await and cancellation
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · .NET 10 LTS SDK 10.0.404 (runtime 10.0.15, C# 14) · mcr.microsoft.com/dotnet/sdk:10.0
You will build a .NET 10 console app that downloads reports from a deliberately slow local API in parallel, streams results with await foreach, gives up on time budgets and stops cleanly when you press Ctrl+C.
On this page
Most of the time a backend program spends is spent waiting: for a database, for another team's API, for a file on a network share. async and await let a C# program wait without holding a thread hostage, so one process can keep hundreds of calls in flight. They do not, on their own, make the program give up. A call to a hung service still waits forever unless something tells it to stop, and that something is a CancellationToken.
In this tutorial you build three small projects in one solution:
- SlowApi, a local ASP.NET Core API that answers after a delay you choose, and streams lines slowly. It stands in for the slow service you depend on, and it logs when a caller hangs up.
- Reports.Client, a class library with a
ReportClientthat calls SlowApi. This is the code you make correct, one step at a time. - Fetcher, a console app that uses the library. It ends up fetching ten reports with a time budget for each, and stops cleanly on Ctrl+C.
On the way you see what await does to the thread, run calls in parallel with Task.WhenAll, pass a token through every layer, read a stream with await foreach, decide where ConfigureAwait(false) belongs, and watch the three classic bugs happen: async void, fire-and-forget and blocking on .Result.
The tutorial pins .NET 10, the long-term support (LTS) release. .NET 11 is out as a standard-term release; everything here works the same on it.
Time budgets matter most when your users are on slow or expensive connections. Someone on prepaid mobile data on a low-end Android phone will close the app if a screen hangs; the server should notice and stop the work, not finish it for nobody.
Step 1 · Create the solution and the slow API
dotnet --versionMake a throwaway folder with a solution, a web project, a class library and a console app, and let the console app use the library:
mkdir -p ~/async-reports-demo
cd ~/async-reports-demo
dotnet new sln -n AsyncReports
dotnet new web -o SlowApi
dotnet new classlib -o Reports.Client
dotnet new console -o Fetcher
rm Reports.Client/Class1.cs
dotnet sln add SlowApi/SlowApi.csproj Reports.Client/Reports.Client.csproj Fetcher/Fetcher.csproj
dotnet add Fetcher/Fetcher.csproj reference Reports.Client/Reports.Client.csprojFix the API's port at 5090 so every command in this tutorial matches your machine:
cat > SlowApi/Properties/launchSettings.json <<'JSON'
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": false,
"applicationUrl": "http://localhost:5090",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
JSONNow write the API. It has two endpoints. /reports/{id} waits delay milliseconds and returns one line of text; IDs above 99 do not exist. /payments writes count lines, one every delay milliseconds, flushing each so it reaches the caller straight away. Both take a CancellationToken, which ASP.NET Core fills with the request's "client has gone" signal, and both log when that signal fires:
cat > SlowApi/Program.cs <<'CS'
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// GET /reports/7?delay=1500 answers after 1.5 s, or stops early if the caller hangs up.
app.MapGet("/reports/{id:int}", async (int id, int? delay, ILogger<Program> log, CancellationToken ct) =>
{
if (id > 99)
{
return Results.NotFound();
}
try
{
await Task.Delay(delay ?? 1000, ct);
}
catch (OperationCanceledException)
{
log.LogWarning("Report {Id}: the client gave up", id);
return Results.Empty;
}
return Results.Text($"Report {id}: {id * 7} payments");
});
// GET /payments?count=10&delay=300 streams one line every 300 ms.
app.MapGet("/payments", async (int? count, int? delay, HttpResponse response, ILogger<Program> log, CancellationToken ct) =>
{
response.ContentType = "text/plain; charset=utf-8";
var sent = 0;
try
{
for (var i = 1; i <= (count ?? 5); i++)
{
await Task.Delay(delay ?? 300, ct);
await response.WriteAsync($"payment {i}: {i * 1500} NGN\n", ct);
await response.Body.FlushAsync(ct);
sent++;
}
}
catch (Exception ex) when (ex is OperationCanceledException or IOException)
{
log.LogWarning("Payments stream: the client left after {Sent} lines", sent);
}
});
app.Run();
CSOpen a second terminal and start the API. Leave it running for the rest of the tutorial; its log is where you see the server notice cancelled calls:
cd ~/async-reports-demo/SlowApi
dotnet runBack in the first terminal, ask for a report with a 1.5 second delay, a report that does not exist, and three streamed lines:
curl -s -w ' (%{time_total} s)\n' "http://localhost:5090/reports/3?delay=1500"
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5090/reports/404
curl -sN "http://localhost:5090/payments?count=3"Check it worked
The second terminal shows Now listening on: http://localhost:5090. The first curl prints Report 3: 21 payments with a time a little over 1.5 seconds, the second prints 404, and the three payment lines appear about 300 milliseconds apart rather than all at once. ls ~/async-reports-demo shows AsyncReports.slnx, Fetcher, Reports.Client and SlowApi.
Step 2 · Write an async method and watch the thread
Create the client in the library. GetReportAsync is an async method that returns Task<string>: a promise of a string that will exist later. Each await hands back a task that is not finished yet, and the method pauses there:
cd ~/async-reports-demo
cat > Reports.Client/ReportClient.cs <<'CS'
namespace Reports.Client;
public sealed class ReportClient(HttpClient http)
{
public async Task<string> GetReportAsync(int id, int delayMs)
{
using HttpResponseMessage response = await http.GetAsync($"reports/{id}?delay={delayMs}");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
CSNow fetch three reports, one after the other, and print which thread the code is on before and after each await:
cat > Fetcher/Program.cs <<'CS'
using System.Diagnostics;
using Reports.Client;
using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5090/") };
var client = new ReportClient(http);
var clock = Stopwatch.StartNew();
foreach (var id in new[] { 1, 2, 3 })
{
Console.WriteLine($"Asking for report {id} on thread {Environment.CurrentManagedThreadId}");
var report = await client.GetReportAsync(id, delayMs: 1000);
Console.WriteLine($" {report} (carried on on thread {Environment.CurrentManagedThreadId})");
}
Console.WriteLine($"One at a time: 3 reports in {clock.ElapsedMilliseconds} ms");
CS
dotnet run --project FetcherHere is what happens at await http.GetAsync(...). The request goes out, and GetAsync returns a task that is not complete. Instead of blocking, the method returns to its caller and the thread is free for other work. When the response arrives, the rest of the method (the continuation) is scheduled to run. A console app has no SynchronizationContext, the hook that UI frameworks use to send continuations back to a particular thread, so the continuation runs on whichever thread-pool thread is free. That is why the thread number can change.
using var http = new HttpClient is fine for a short-lived tool. In a long-running service, create one HttpClient and reuse it, or let IHttpClientFactory manage them, so you do not run out of sockets.
Check it worked
The output looks something like this, with your own thread numbers and times:
Asking for report 1 on thread 1
Report 1: 7 payments (carried on on thread 9)
Asking for report 2 on thread 9
Report 2: 14 payments (carried on on thread 9)
Asking for report 3 on thread 9
Report 3: 21 payments (carried on on thread 6)
One at a time: 3 reports in 3201 msThe total is over 3000 ms: each await waited for its report before the next request started. The code is asynchronous but not parallel.
Step 3 · Run the calls in parallel with Task.WhenAll
Calling an async method starts its work straight away and gives you the task. If you start all three before awaiting any of them, the waits overlap. Task.WhenAll gives you one task that finishes when all of them have.
The second half of this program sends a batch with a bad ID in the middle, to show what a failure looks like:
cat > Fetcher/Program.cs <<'CS'
using System.Diagnostics;
using Reports.Client;
using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5090/") };
var client = new ReportClient(http);
// Start all three downloads first, then wait for them together.
var clock = Stopwatch.StartNew();
Task<string>[] downloads = new[] { 1, 2, 3 }
.Select(id => client.GetReportAsync(id, delayMs: 1000))
.ToArray();
string[] reports = await Task.WhenAll(downloads);
foreach (var report in reports)
{
Console.WriteLine($" {report}");
}
Console.WriteLine($"Together: {reports.Length} reports in {clock.ElapsedMilliseconds} ms");
// One bad ID: await rethrows the first failure, and the other tasks still finish.
Task<string>[] batch = new[] { 4, 404, 5 }
.Select(id => client.GetReportAsync(id, delayMs: 1000))
.ToArray();
try
{
await Task.WhenAll(batch);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Batch failed: {ex.Message}");
}
foreach (var task in batch)
{
// .Result is safe here only because WhenAll has finished: the task is already complete.
var outcome = task.IsCompletedSuccessfully ? task.Result : task.Exception!.InnerException!.Message;
Console.WriteLine($" {task.Status,-16} {outcome}");
}
CS
dotnet run --project Fetcher.ToArray() matters. Select is lazy: it describes the calls but does not make them until something reads it. Turning it into an array starts all three at once and gives you tasks you can inspect afterwards. A lazy query that you read twice would send every request twice.
When you await a WhenAll task and one of the inner tasks failed, you get the first exception. The others are not lost: each task's own Status and Exception tell you what happened to it, which is how the loop at the end reports each one.
Check it worked
The first three reports arrive in a little over 1000 ms in total, not 3000. The batch prints something like Batch failed: Response status code does not indicate success: 404 (Not Found). and then one line per task: RanToCompletion for reports 4 and 5 and Faulted for 404. Even though the 404 came back at once, WhenAll waited a full second for the other two.
Step 4 · Pass a CancellationToken through every layer
Right now nothing limits how long a report may take. HttpClient has its own Timeout, but it defaults to 100 seconds and covers each request separately, not a batch. Give the caller control instead: the library method takes a CancellationToken and passes it to every call that accepts one.
The conventions, which the .NET libraries follow too: the token is the last parameter, it is called cancellationToken, and in a public method it defaults to default (a token that never cancels) so callers who do not care can leave it out:
cat > Reports.Client/ReportClient.cs <<'CS'
namespace Reports.Client;
public sealed class ReportClient(HttpClient http)
{
public async Task<string> GetReportAsync(int id, int delayMs, CancellationToken cancellationToken = default)
{
using HttpResponseMessage response = await http.GetAsync($"reports/{id}?delay={delayMs}", cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(cancellationToken);
}
}
CSIn the app, a CancellationTokenSource owns the token. Created with a TimeSpan, it cancels itself when the time is up. Here the whole batch gets two seconds, and the reports take 1.5, 3 and 4.5 seconds:
cat > Fetcher/Program.cs <<'CS'
using System.Diagnostics;
using Reports.Client;
using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5090/") };
var client = new ReportClient(http);
// The whole batch gets 2 seconds. The same token goes to every call.
using var budget = new CancellationTokenSource(TimeSpan.FromSeconds(2));
var clock = Stopwatch.StartNew();
Task<string>[] downloads = new[] { 1, 2, 3 }
.Select(id => client.GetReportAsync(id, delayMs: id * 1500, budget.Token))
.ToArray();
try
{
string[] reports = await Task.WhenAll(downloads);
Console.WriteLine($"All {reports.Length} reports arrived in {clock.ElapsedMilliseconds} ms");
}
catch (OperationCanceledException) when (budget.IsCancellationRequested)
{
Console.WriteLine($"Gave up after {clock.ElapsedMilliseconds} ms: the 2 s budget ran out");
}
foreach (var task in downloads)
{
Console.WriteLine($" {task.Status,-16} {(task.IsCompletedSuccessfully ? task.Result : "-")}");
}
CS
dotnet run --project FetcherFollow the token. budget.Token goes into GetReportAsync, which hands it to GetAsync. When the two seconds are up, HttpClient abandons the request and closes the connection. On the server, ASP.NET Core sees the connection close and cancels the request's token, which Task.Delay was watching, so the server stops too. One signal stopped work in three places.
Cancellation shows up as an OperationCanceledException (HttpClient throws its subclass, TaskCanceledException). The when (budget.IsCancellationRequested) filter catches it only if your budget caused it, so a cancellation from somewhere else still surfaces. Analyser rule CA2016 suggests passing a token you have into calls that accept one, so your editor shows a hint where you forget.
Check it worked
The app prints Gave up after and a number close to 2000 ms, then RanToCompletion for report 1 and Canceled for reports 2 and 3. The API's terminal shows two warnings, something like Report 2: the client gave up and Report 3: the client gave up. Without the token, the app would have waited the full 4.5 seconds and the server would have done all the work anyway.
Step 5 · Stream results with IAsyncEnumerable and await foreach
Some data arrives a piece at a time: log lines, rows from a query, messages from a queue. An async method that returns IAsyncEnumerable<T> can yield return each piece as it arrives, and the caller reads them with await foreach.
Add a method to the client that reads the /payments stream line by line:
cat > Reports.Client/ReportClient.cs <<'CS'
using System.Runtime.CompilerServices;
namespace Reports.Client;
public sealed class ReportClient(HttpClient http)
{
public async Task<string> GetReportAsync(int id, int delayMs, CancellationToken cancellationToken = default)
{
using HttpResponseMessage response = await http.GetAsync($"reports/{id}?delay={delayMs}", cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(cancellationToken);
}
public async IAsyncEnumerable<string> StreamPaymentsAsync(int count, int delayMs,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// ResponseHeadersRead: start reading as soon as the headers arrive, not after the whole body.
using HttpResponseMessage response = await http.GetAsync(
$"payments?count={count}&delay={delayMs}", HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
using var reader = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
while (await reader.ReadLineAsync(cancellationToken) is { } line)
{
yield return line;
}
}
}
CSTwo details make the streaming real. Without HttpCompletionOption.ResponseHeadersRead, GetAsync would download the whole body into memory before returning, and the "stream" would arrive all at once. And [EnumeratorCancellation] connects the token to the enumeration, so a caller can also attach one later with .WithCancellation(token) on an enumerable someone else created; the compiler warns (CS8425) if an async iterator takes a token without it.
Read ten lines at 300 ms each, with a two-second budget:
cat > Fetcher/Program.cs <<'CS'
using System.Diagnostics;
using Reports.Client;
using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5090/") };
var client = new ReportClient(http);
using var budget = new CancellationTokenSource(TimeSpan.FromSeconds(2));
var clock = Stopwatch.StartNew();
var received = 0;
try
{
await foreach (var line in client.StreamPaymentsAsync(count: 10, delayMs: 300, budget.Token))
{
received++;
Console.WriteLine($"{clock.ElapsedMilliseconds,5} ms {line}");
}
Console.WriteLine($"Stream finished: {received} lines");
}
catch (OperationCanceledException) when (budget.IsCancellationRequested)
{
Console.WriteLine($"Stopped after {received} lines: the 2 s budget ran out");
}
CS
dotnet run --project FetcherCheck it worked
Lines appear one by one, roughly 300 ms apart, each with its own timestamp, for example 612 ms payment 1: 1500 NGN. After about two seconds the app prints something like Stopped after 6 lines: the 2 s budget ran out. The API's terminal shows Payments stream: the client left after and a line count.
Step 6 · Use ConfigureAwait(false) in library code
When an await finishes, the continuation goes back to the SynchronizationContext that was current when it started, if there is one. Desktop and mobile UI frameworks (WPF, Windows Forms, .NET MAUI) have one, so code after an await in a button handler runs on the UI thread again, which it needs to update the screen. Console apps and ASP.NET Core have none.
A library does not know who will call it. Its code never needs to return to a UI thread, so it should say so with ConfigureAwait(false) on every await. That skips the trip back, and it stops the library from taking part in the deadlock you meet in the next step. Application code, especially UI code that touches controls after an await, should leave it out.
Turn on analyser rule CA2007, which flags every await without ConfigureAwait, for the library only:
cat > Reports.Client/.editorconfig <<'INI'
[*.cs]
dotnet_diagnostic.CA2007.severity = warning
INI
dotnet build Reports.Client/Reports.Client.csproj --no-incremental 2>&1 | grep CA2007 | sort -uNow add ConfigureAwait(false) to each await. This is the finished library:
cat > Reports.Client/ReportClient.cs <<'CS'
using System.Runtime.CompilerServices;
namespace Reports.Client;
public sealed class ReportClient(HttpClient http)
{
public async Task<string> GetReportAsync(int id, int delayMs, CancellationToken cancellationToken = default)
{
using HttpResponseMessage response = await http
.GetAsync($"reports/{id}?delay={delayMs}", cancellationToken)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
}
public async IAsyncEnumerable<string> StreamPaymentsAsync(int count, int delayMs,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// ResponseHeadersRead: start reading as soon as the headers arrive, not after the whole body.
using HttpResponseMessage response = await http
.GetAsync($"payments?count={count}&delay={delayMs}", HttpCompletionOption.ResponseHeadersRead, cancellationToken)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
using var reader = new StreamReader(
await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false));
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
{
yield return line;
}
}
}
CS
dotnet build Reports.Client/Reports.Client.csproj --no-incrementalThe rule lives in Reports.Client/.editorconfig, so Fetcher and SlowApi are not affected: they are applications, and there ConfigureAwait(false) is noise at best.
Check it worked
The first build lists CA2007 warnings such as warning CA2007: Consider calling ConfigureAwait on the awaited task, one for each await in ReportClient.cs. The second build ends with Build succeeded and no CA2007 lines. Running dotnet run --project Fetcher again gives the same streamed output as before: in a console app the change makes no visible difference, which is the point.
Step 7 · Watch the three classic async bugs happen
Make a separate console project for the mistakes, so they cannot leak into the real app:
dotnet new console -o Pitfalls
cat > Pitfalls/Program.cs <<'CS'
// Bug 1: fire and forget. The exception is stored in a task that nobody awaits.
_ = SaveAuditAsync("fire and forget");
await Task.Delay(300);
Console.WriteLine("1. Fire and forget: the program carried on and nobody saw the error.");
// The fix: keep the task and await it, so the exception reaches you.
try
{
await SaveAuditAsync("awaited");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($" Awaited instead: caught \"{ex.Message}\"");
}
// Bug 2: async void. The caller gets no task, so it cannot wait for it or catch its errors.
try
{
WriteLogAsyncVoid();
}
catch (InvalidOperationException)
{
Console.WriteLine("Never printed: the exception does not come back to this catch.");
}
Console.WriteLine("2. async void: the call returned at once. The exception is on its way...");
await Task.Delay(500);
Console.WriteLine("Never printed either: the process has crashed by now.");
static async Task SaveAuditAsync(string how)
{
await Task.Delay(100);
throw new InvalidOperationException($"audit store is down ({how})");
}
static async void WriteLogAsyncVoid()
{
await Task.Delay(100);
throw new InvalidOperationException("log store is down (async void)");
}
CSRun it. It is meant to crash, so the command prints the exit code when it does:
dotnet run --project Pitfalls || echo "exit code: $?"What each bug does, and what to do instead:
- Fire and forget. The first
SaveAuditAsyncfailed, and the program never knew. If you call an async method and drop the task, the compiler warns (CS4014); writing_ =silences the warning, not the problem. Await the task, or if it really must run in the background, hand it to something that awaits it and logs failures, such as a hosted service in ASP.NET Core. - async void. An exception thrown from an
async voidmethod has no task to live in, so it is raised on the thread pool and ends the process. Thetry/catcharound the call cannot see it, because the method returned to the caller at its firstawait. Useasync Taskeverywhere. The one placeasync voidis needed is an event handler, such as a button'sClick, and that handler should catch its own exceptions. - Blocking with .Result or .Wait(). Not in the program, because in a console app it only wastes a thread. In a WPF or Windows Forms click handler, this freezes the window for good:
// Inside a button click handler: never do this.
var report = client.GetReportAsync(1, 1000).Result;The UI thread stops at .Result and waits for the task. The task's continuation is waiting for the UI thread, which is the SynchronizationContext it captured. Each waits for the other: a deadlock. ConfigureAwait(false) inside the library would let the library's continuations run elsewhere, but any library without it brings the deadlock back. In ASP.NET Core there is no deadlock, but every blocked request holds a thread-pool thread doing nothing, and under load the pool runs out. The fix is the same everywhere: await all the way up, from the call site to Main or the event handler.
Check it worked
The output starts with 1. Fire and forget: the program carried on and nobody saw the error., then Awaited instead: caught "audit store is down (awaited)", then the 2. async void line. Then it ends with Unhandled exception. System.InvalidOperationException: log store is down (async void), a stack trace and a non-zero exit code. Neither Never printed line appears.
Step 8 · Stop the console app cleanly on Ctrl+C
By default, Ctrl+C ends a .NET process on the spot: no finally blocks, no "stopped after 4 of 10" message, half-written files left behind. Console.CancelKeyPress lets you turn the keypress into a cancelled token instead. Setting e.Cancel = true keeps the process alive, so the code that is running can see the token, stop and tidy up. A second Ctrl+C is left alone, so it still ends a program that is stuck.
This is the finished app. It fetches ten reports, one at a time. Each one gets its own three-second budget from a linked token source, which cancels when either its own timer fires or its parent, the Ctrl+C token, is cancelled. Report 7 takes five seconds, so it is skipped:
cat > Fetcher/Program.cs <<'CS'
using System.Diagnostics;
using Reports.Client;
using var stop = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
if (stop.IsCancellationRequested)
{
return; // second Ctrl+C: let .NET end the process straight away
}
e.Cancel = true; // first Ctrl+C: keep running so the code below can stop cleanly
Console.WriteLine("Ctrl+C received, stopping...");
stop.Cancel();
};
using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5090/") };
var client = new ReportClient(http);
var clock = Stopwatch.StartNew();
var fetched = 0;
try
{
for (var id = 1; id <= 10; id++)
{
// Each report gets 3 s of its own, and Ctrl+C still stops it early.
using var budget = CancellationTokenSource.CreateLinkedTokenSource(stop.Token);
budget.CancelAfter(TimeSpan.FromSeconds(3));
try
{
var report = await client.GetReportAsync(id, delayMs: id == 7 ? 5000 : 800, budget.Token);
fetched++;
Console.WriteLine($"{clock.ElapsedMilliseconds,6} ms {report}");
}
catch (OperationCanceledException) when (!stop.IsCancellationRequested)
{
Console.WriteLine($"{clock.ElapsedMilliseconds,6} ms Report {id} took longer than 3 s, skipped");
}
}
}
catch (OperationCanceledException) when (stop.IsCancellationRequested)
{
Console.WriteLine($"Stopped cleanly after {clock.ElapsedMilliseconds} ms: {fetched} of 10 reports fetched.");
return 130; // the usual exit code for a program stopped by Ctrl+C
}
Console.WriteLine($"Done in {clock.ElapsedMilliseconds} ms: {fetched} of 10 reports fetched.");
return 0;
CS
dotnet run --project FetcherThe inner catch handles a report that ran out of its own time, and only that: its filter is false when Ctrl+C caused the cancellation, so that exception carries on to the outer catch, which ends the loop. Every layer underneath, GetReportAsync, HttpClient and the server's Task.Delay, already stops when the token does, because you passed it all the way down.
The full run takes about ten seconds. Run it again, and this time press Ctrl+C after three or four reports. Then print the exit code:
dotnet run --project Fetcher
echo "exit code: $?"Console.CancelKeyPress covers Ctrl+C in a terminal. When the same app runs as a service or in a container, it is stopped with SIGTERM instead; PosixSignalRegistration.Create(PosixSignal.SIGTERM, ...) lets you handle that the same way, and ASP.NET Core and the .NET Generic Host do it for you.
Check it worked
The full run lists nine reports, the line Report 7 took longer than 3 s, skipped after about eight seconds, and Done in with 9 of 10 reports fetched. at the end. In the Ctrl+C run, the terminal shows ^C, then Ctrl+C received, stopping... and Stopped cleanly after with fewer than 10 reports, and exit code: 130. The API's terminal shows the client gave up for the report that was in flight when you pressed the keys.
Step 9 · Clean up
Stop the API with Ctrl+C in its terminal:
# In the second terminal, where dotnet run for SlowApi is running, press Ctrl+C.Then remove the project folder. The .NET SDK stays installed:
cd ~
rm -rf ~/async-reports-demoCheck it worked
curl -s http://localhost:5090/ fails to connect, and ls ~/async-reports-demo reports No such file or directory.
Next steps
- Put the same token handling into an HTTP service, where ASP.NET Core passes each request's token to your endpoint: build a minimal API with ASP.NET Core in .NET 10.
- Shape the reports you download with
Where,GroupByandSum: query collections in C# with LINQ. - Compare the same ideas in another language, where a
context.Contextplays the part of the token: cancel slow work in Go with context and timeouts. - See how Python's
asynciohandles many calls at once: run many network calls at once with Python asyncio.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials