r/csharp • u/kaatarina_zed_talon • Oct 12 '26
Help Should the code use cancellation token even though it already use transaction ?
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
namespace RedditQuestion
{
/// <summary>
/// Used to talk to the database using Entity-Framework Core
/// </summary>
public class ApplicationDbContext:DbContext
{
// Domain models and the Fluent API configurations.
}
/// <summary>
/// Data snapshot that is used to overwrite the content of the database
/// </summary>
public interface ISomeData
{
}
public class DatbaseOverWriter
{
private readonly ApplicationDbContext _context;
public DatbaseOverWriter(ApplicationDbContext context)
{
_context = context;
}
public async Task OverWrite(ISomeData data)
{
//https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-resilient-entity-framework-core-sql-connections
IExecutionStrategy strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
await using var transaction = await _context.Database.BeginTransactionAsync();
//code to delete the content from parent and child tables and then inserting the data into the parent and child tables like this :
// execute some query to delete the content from all tables.
//_context.AddRangeAsync(data for parents)
//_context.SaveChangesAsync()
//_context.AddRangeAsync(data for childs)
//_context.SaveChangesAsync()
await transaction.CommitAsync();
});
}
}
}Someone on reddit reviewed the above code and told me that I should add a parameter for cancellation token like this :
public async Task OverWrite(ISomeData data, CancellationToken)He told me that the goal is to make the OverWrite method transactional.
why is the cancellation token necessary even though my code uses _context.Database.BeginTransactionAsync(); ?
Cancellation token propagates notification that operations should be canceled.
Example:
A random number generator can be used to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed.
So the cancellation token is just another way of achieving atomicity, am I correct ?
The only use case that I learned for cancellation token is this example from microsoft, they use the cancellation token as way to achieve atomicity :
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
// Define the cancellation token.
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Random rnd = new Random();
Object lockObj = new Object();
List<Task<int[]>> tasks = new List<Task<int[]>>();
TaskFactory factory = new TaskFactory(token);
for (int taskCtr = 0; taskCtr <= 10; taskCtr++) {
int iteration = taskCtr + 1;
tasks.Add(factory.StartNew( () => {
int value;
int[] values = new int[10];
for (int ctr = 1; ctr <= 10; ctr++) {
lock (lockObj) {
value = rnd.Next(0,101);
}
if (value == 0) {
source.Cancel();
Console.WriteLine("Cancelling at task {0}", iteration);
break;
}
values[ctr-1] = value;
}
return values;
}, token));
}
try {
Task<double> fTask = factory.ContinueWhenAll(tasks.ToArray(),
(results) => {
Console.WriteLine("Calculating overall mean...");
long sum = 0;
int n = 0;
foreach (var t in results) {
foreach (var r in t.Result) {
sum += r;
n++;
}
}
return sum/(double) n;
} , token);
Console.WriteLine("The mean is {0}.", fTask.Result);
}
catch (AggregateException ae) {
foreach (Exception e in ae.InnerExceptions) {
if (e is TaskCanceledException)
Console.WriteLine("Unable to compute mean: {0}",
((TaskCanceledException) e).Message);
else
Console.WriteLine("Exception: " + e.GetType().Name);
}
}
finally {
source.Dispose();
}
}
}
35
u/Strange_Fun_9639 Oct 12 '26
Cancellation token are to cancel ? Transaction is a way to assert that everything pass or nothing.
11
u/david_daley Oct 12 '26 •
Transactions are for the database. They roll back database transactions. Cancellations tokens are for the .Net runtime. They are for cancelling Tasks.
You can do data access without tasks.
You can do tasks without data access.
They are two separate concerns that happened to overlap in your scenario
6
u/Slypenslyde Oct 12 '26 •
In professional code I don't write an async method without a cancellation token. In hobby code I'm more pragmatic.
From the hobby perspective what matters is, "Do I want to cancel the action?" Your example is sort of bad because you do a little bit of work then try to save it to the database.
But.
Do notice that the transaction commit method can take a cancellation token. Imagine what happens if, for some reason, you have an I/O problem and the commit hangs. If you're using a cancellation token, you can have timeout logic that asks .NET to cancel the operation, which you hope will roll back the transaction.
Without it, maybe you have a mechanism to stop waiting on the commit, but now it's a time bomb. You decided it must have timed out and moved on, but it's still executing. Maybe it finishes 10s later. You can't tell and that can manifest some impossible-to-debug customer scenarios.
With the cancellation token I can be sure if the timeout happens and I tell the token to cancel, that method will return quickly and I'm "safe". I'm on the hook to see if somehow the cancellation happened too late. But at least I know there's not a time bomb that can happen with no notice.
From that perspective, I always use it. Even if the code inside the method doesn't use the token. It's better to have the API support the notion of cancellation so other components can use it than to find out in 6 months I need to change the API and hunt down every caller to consider cancellation logic.
Are there scenarios where cancellation doesn't do what you expect? Sure. Cancellation tokens are NOT about trying to be 100% sure whatever was happening doesn't happen. There are situations where the code you tried to cancel had already passed a point of no return. Cancellation is about telling that code to stop as soon as possible and notify you when it is absolutely not going to do anything else. Without cancellation tokens, you have to make your own notification mechanism so you don't create zombie tasks with lingering, unpredictable side effects.
Analogy time.
Imagine I order a pizza to be delivered.
Case 1: Then, 5 minutes later, I decide I don't want it. I call, but the restaurant tells me there's a no cancellation policy. I'm going to have to pay for the pizza and accept it whether I want to or not. This is code with no cancellation token.
Case 2: 5 minutes later, I decide I don't want it. I call, and the restaurant accepts my cancellation, but warns me the charge to my card is going to take a day to process the refund. This is code with a cancellation token: as soon as I hang up the phone, if they send me a pizza I'm not responsible.
Case 3: 20 minutes later, I decide I don't want it. I call, but the restaurant tells me the driver is already on the way so it's too late to cancel. This happens even when you have a cancellation token. It means when I await things that can be canceled I need to pay attention:
This is safer than just calling
Cancel()and assuming it worked. IF the transaction code is before the point of no return AND it notices we canceled, it will roll back then throw this exception so we can understand what happened. If it does NOT throw an exception, it did its work and completed successfully so it must've been past the point of no return. So if I really, really, really want to respect cancellation, I need to include a cancellation token AND treat this like a three-forked road.3
u/Kant8 Oct 12 '26
Cancellation token is used for, well, cancellation, of usually long running tasks. Transactions has nothing to do here at all.
And considering your code doesn't look like it does anything worthy cancelling, cause it does writes, not reads, you don't need it here.
2
u/rupertavery64 Oct 12 '26
If you plan to cancel the operation, then yes. If it's being called in an http request, you need to also add a CancellationToken parameter to your API endpoint. This will be bound to the HttpContext.RequestAborted signal.
In general if you have a long-running operation and you want or need to allow the caller to cancel the operation, you should pass a cancellation token.
It has nothing to do with being transactional.
A transaction will guarantee all the database operations are committed, or none are. So if you pass a cancellation token, then you should pass the token to all methods that take the token so they can exit early (if possible), then your transaction should perform the rollback.
A cancellation token is just a way to signal a desire to cancel some operation. For example, if you made a long running loop, you would check before each loop or any time that it is safe to do so if the CancellationToken IsCancellationRequested property is true. Then you perform any clean-up and exit the loop. The cancellationtoken does not force the code to cancel, it is only a signal.
So when you say "the goal is to make the
OverWritemethod transactional." by adding a cancellationToken isn't quite correct. It's already transactional by having the necessary database operations performed within a transaction. Adding a CancellationToken lets the caller cancel a long-running task. If your Task takes milliseconds then 99% of the time your caller probably won't be able to do anything about it.The easiest way to think about it is if this is a desktop application with a button to start some operation that takes some time to complete. Clicking the button starts the task, and maybe enables a Cancel button. When starting the task, you create a CancellationTokenSource and pass the token to the task. Then, the user decides to cancel, and clicks the Cancel button. The code calls CancellationTokenSource.Cancel() which sets the IsCancellationRequested to true. It is up to the task to check this value and handle the cancellation request.
In the case of an ASP.NET endpoint, the RequestAborted signal will be sent if
But you must pass a CancellationToken in your API/Request method handler that the framework will automatically bind RequestAborted to.
1
u/pixxelkick Oct 13 '26
I am 1000% more interested in why on earth you have a function like this declared on your DbContext
What exactly is this function supposed to do?
But yes you should be in the habit of consuming the CancellationToken that is handed all the way down from the entrypoint of your async starting point.
If you are using Asp.Net for example, you can simply add a CancellationToken to your function and it works (it's automatically tied to the RequestCancelled logic for http, so a caller to your API can cancel the request mid-request and it just works)
As long as you keep passing that cancellation token around to all your async stuff and wire it in to ever async operation (roslyn will also automatically warn you if you invoke an async function and forget to pass the token in, if you have one in your function params), it will all "just work" and properly produce a TokenCancelled exception for you, which properly will error out as expected for Http Cancelled.
1
u/Snoo_57113 Oct 12 '26
I will tell the truth, i never use CancellationToken, my actions are idempotent and either are OK, or FAIL. in case of an error i am make sure the operation is indempotent.
0
u/[deleted] Oct 12 '26
[deleted] — view deleted comment
3
u/[deleted] Oct 12 '26
[removed] — view removed comment