Here’s the translation of the Go code to C# with explanations in Markdown format suitable for Hugo:
Our first example demonstrates the usage of HttpContext for controlling cancellation in an ASP.NET Core application. The HttpContext carries request-scoped values and cancellation signals across the application.
In this C# example, we’re using ASP.NET Core to set up a simple HTTP server. The HandleHelloRequest method simulates some work the server is doing, while keeping an eye on the cancellation token for a signal that we should cancel the work and return as soon as possible.
To run the server:
Simulate a client request to /hello, hitting Ctrl+C shortly after starting to signal cancellation:
In this example, the HttpContext.RequestAborted property provides a CancellationToken that is triggered when the request is aborted. This is similar to the context.Done() channel in the original Go example.
The try-catch block in the HandleHelloRequest method catches the TaskCanceledException that is thrown when the task is cancelled. This is equivalent to checking the ctx.Err() in the Go version.
Note that ASP.NET Core automatically handles a lot of the setup that we had to do manually in the Go version, such as creating the server and routing requests.