We have a long-running operation that read millions of records in a loop. I was wondering if I should call ThrowIfCancellationRequested
in that loop (which would mean it is executed N times), or should I do it only every 1000th time?
So my question really is: how expensive is a call to ThrowIfCancellationRequested? Does it involve database reading?
Yes, it does involve database querying, but only one query is being issued:
_shutdownToken.ThrowIfCancellationRequested();
if (IsJobAborted())
{
throw new JobAbortedException();
}
}
private bool IsJobAborted()
{
var state = _connection.GetStateData(_jobId);
if (state == null)
{
return true;
}
if (!state.Name.Equals(ProcessingState.StateName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
And some deserialization stuff in SQL Server implementation:
CreatedAt = jobData.CreatedAt,
LoadException = loadException
};
});
}
public override StateData GetStateData(string jobId)
{
if (jobId == null) throw new ArgumentNullException(nameof(jobId));
string sql =
$@"select s.Name, s.Reason, s.Data
from [{_storage.SchemaName}].State s with (readcommittedlock)
inner join [{_storage.SchemaName}].Job j with (readcommittedlock) on j.StateId = s.Id
where j.Id = @jobId";
return _storage.UseConnection(_dedicatedConnection, connection =>
{
var sqlState = connection.Query<SqlState>(sql, new { jobId = long.Parse(jobId) }, commandTimeout: _storage.CommandTimeout).SingleOrDefault();
if (sqlState == null)
{
Thanks. So in a loop, this is prohibitive. I’ll make sure, it is only being executed once every 3 secs or so for a performing UI cancelling button.
1 Like