Is this a good practice to always add CancellationToken in my actions no matter if operation is long or not?
I'm currently adding it to every action and I don't know if it's right or wrong.
[ApiController]
[Route("api/[controller]")]
public class DummiesController : ControllerBase
{
private readonly AppDbContext _dbContext;
public DummyController(AppDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet("{id}")]
public async Task<ActionResult<Dummy>> GetAsync(int id, CancellationToken ct) // <<----- should I always do this?
{
var dummy = await _dbContext.Dummies.AsNoTracking().SingleOrDefaultAsync(e=>e.Id == id, ct);
if (dummy == null) return NotFound();
return dummy;
}
}
Also is adding CancellationToken ct = default(CancellationToken)
necessary?
CancellationToken
object doesn't magically cancel anything by itself. You have to cancel it yourself. – Qualmish