Adding a CancellationToken to minimal API endpoints

259 Views Asked by At

I've got a SQL server table with 32 items, it does not grow. Along with a basic stored procedure which selects them.

select * from Codes

Then there is a minimal API around the stored proc which just queries the codes, it take no time.

app.MapGet("/getcodes", async ([FromServices] MyService service) =>
{
    return await service.GetCodes();
});

Now I'm wondering if it would make a difference to add a CancellationToken to these kinds of really short functions?

app.MapGet("/getcodes", async (CancellationToken  ct, [FromServices] MyService service) =>
{
    return await service.GetCodes(ct);
});
public async Task<Codes> GetCodes(CancellationToken ct)
{
    await using SqlConnection cn = new(_connectionString);
    await cn.OpenAsync(ct);
    await using SqlCommand cmd = new(...);
    await using var reader = await cmd.ExecuteReaderAsync(ct);

Would it help to add CancellationToken? Only time this would take really long is when the database server is down and Connection.OpenAsync times out.

Or is it more standard practice to always add a cancellationtoken to endpoints or don't when endpoints don't take long? The await's generate more overhead then the actual query right

1

There are 1 best solutions below

0
On BEST ANSWER

In general, adding a CancellationToken to your asynchronous transactions is a good practice as it provides better cancellation support and responsiveness in your application. However, in the specific case you describe, where the transaction is very short and the potential delay is mostly due to external factors (such as the database server being down), it may not provide a significant benefit.

The purpose of CancellationToken is to allow the cancellation of long duration transactions, especially those involving I/O or other external resources. In short, quick operations such as querying a small static dataset from a database may not benefit much from a CancellationToken.

In summary, adding a CancellationToken may not provide significant benefits for your specific case, but it may be a valid consideration for consistency or to comply with your project's general coding standards. Always consider the specific requirements and characteristics of your application when deciding whether to use CancellationToken in a particular scenario.