Skip to content

Instantly share code, notes, and snippets.

@Alexei000
Created September 21, 2017 11:18
Show Gist options
  • Save Alexei000/d8f658248a34acd253ed260310765755 to your computer and use it in GitHub Desktop.
Save Alexei000/d8f658248a34acd253ed260310765755 to your computer and use it in GitHub Desktop.
Execute SQL statement with timeout
private void RegisterCommandCancelOnToken(CancellationTokenSource cts, TdCommand command)
{
if (cts == null)
return;
var innerCommand = command;
cts.Token.Register(() =>
{
try
{
// ReSharper disable once AccessToDisposedClosure
var query = command.CommandText;
Logger?.Log(LogLevel.Warn, $"Teradata data access command cancel for: {query}");
innerCommand.Cancel();
}
catch (ObjectDisposedException)
{
// do nothing if object was already disposed
}
});
}
[SuppressMessage("Microsoft.Security", "CA2100")]
public int ExecuteNonQuery(string query, Params parameters, int? runTimeout = null, bool useTransaction = false)
{
var cts = runTimeout.HasValue ? new CancellationTokenSource(runTimeout.Value * 1000) : null;
using (var command = CreateTdCommand(GetConnection(), useTransaction))
{
ConstructCommandParameters(command, parameters);
RegisterCommandCancelOnToken(cts, command);
command.CommandTimeout = runTimeout ?? Constants.Db.DefaultCommandTimeout;
command.CommandText = query;
LogQuery(query);
var ret = command.ExecuteNonQuery();
if (cts?.IsCancellationRequested ?? false)
throw new TimeoutException("Timeout exception while executing non query");
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment