Created
September 21, 2017 11:18
-
-
Save Alexei000/d8f658248a34acd253ed260310765755 to your computer and use it in GitHub Desktop.
Execute SQL statement with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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