i have database query: datareader.execQuery("select * from table");
However sometimes database takes too long to respond and is stuck at this line.
if this happens my application should exit
Thanks guys but i need to know:
Is there any way i can achieve this using Stopwatch or Timer??
You should set the CommandTimeout on your SqlCommand object. If the timeout is exceeded, you will get an exception. You can catch this, and exit your app, if that is what you want to do.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx
"Gets or sets the wait time before terminating the attempt to execute a command and generating an error."
A cleaner way will be to set the SqlCommand.CommandTimeout property by default it is 30 secs
You will have to handle the TimeOut Exception
Related
I have a c# application that calls the same mysql stored procedure multiple times with different parameters. Its called about 250 times and each call takes about 30 seconds to complete.
There are some cases when for some reason a call takes much more time, and it blocks the next ones from running, so I would like to set a timeout for the stored procedures to stop when it takes more than say like 5 minutes. This way the others could still run and only the one that took too much time would be skipped.
I tried to use the command timeout of the mysql connection, but this does not kill the running stored procedure, only throws an exception in code which is not ideail because the next call will start while the previous one is still running.
Is there a way to set a mysql timout for the connection, or just kill a mysql thread/process (the sp) if it takes too much time? Closing the mysql command or connection did not do it, and clearing the connection pool did not help either.
To kill a running stored procedure, use MySqlCommand.Cancel (using the same MySqlCommand object that was used to start that stored procedure). Because MySqlCommand.ExecuteNonQuery (or ExecuteReader, etc.) will block the thread that called it, this will have to be done from another thread. One way to accomplish this would be with CancellationTokenSource, then registering a callback that will cancel the command:
// set up command
using (var command = new MySqlCommand("sproc_name", connection))
{
command.CommandType = CommandType.StoredProcedure;
// register cancellation to occur in five minutes
using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)))
using (cts.Token.Register(() => command.Cancel())
{
// execute the stored procedure as normal
using (var reader = command.ExecuteReader())
{
// use reader, or just call command.ExecuteNonQuery instead if that's what you need
}
}
}
I'm trying to kill query triggered by ADO.NET command on postgresql database, after command timeout:
using (var command = new PgSqlCommand("public.timeout_test", connection))
{
command.CommandTimeout = 10;
command.CommandType = CommandType.StoredProcedure;
connection.Open();
command.ExecuteNonQuery();
}
In dotnet code timeout exception is being throwed correctly, but I wonder why query triggered by timout_test function is still in active state. If I run below query, then query executed by timeout_tets is listed as active:
SELECT * FROM pg_stat_activity where state = 'active';
Tried to test it with devart and npgsql connectors, but both of them behave in the same way, so I assume that it's intended behevior, but don't understand the reason. Also wanted to ask if there is a way to kill query after command timeout.
At least in Npgsql, CommandTimeout is implemented as a client-side socket timeout: after a certain amount of time Npgsql will simply close the network socket on its side. This doesn't cancel the query server-side, which will continue running.
You can set the PostgreSQL statement_timeout parameter to have it kill queries running more than a given amount of time; for best results, set statement_timeout to something lower than CommandTimeout - this will ensure that server timeout occurs before client timeout, preserving the connection and transmitting the server timeout to the client as a regular exception.
Another option is to manually trigger a cancellation from the client by calling NpgsqlCommand.Cancel(). You can do this whenever you want (e.g. when the user clicks a button), but contrary to statement_timeout it will obviously work only if the network is up.
I have created a function app time trigger with C#.
Inside the logic, I call and execute a stored procedure that I have created in SQL Server.
The execution of the stored proc takes more than 8 minutes, and I have got the following error in Azure function apps log :
2018-04-02T11:03:46.409 [Error] Exception while executing function:
Functions.AbarIomWeeklyUsage. mscorlib: Exception has been thrown by
the target of an invocation. .Net SqlClient Data Provider: Execution
Timeout Expired. The timeout period elapsed prior to completion of
the operation or the server is not responding. The wait operation
timed out. 2018-04-02T11:03:46.425 [Error] Function completed
(Failure, Id=1b85e7ef-ea52-4fd3-ab79-f27d188c5cac, Duration=30323ms)
So far I tried 2 things :
1. leverage the connection timeout in application connection string
2. add timeout in host.json
But it still gives me the same error 30 seconds timeout.
Anyone experienced the same or have solution for this?
You are certainly exceeding the default command timeout (the default is 30 seconds). If you don't set SqlCommand.CommandTimeout you will get a SqlException. Set the command's CommandTimeout in code (there is no configuration for this) to 10 minutes (600 seconds), same as your function timeout.
Here's a code snippet on how to do this:
using (SqlCommand cmd = new SqlCommand(text, conn))
{
cmd.CommandTimeout = 60 * 60; // seconds
cmd.Parameters.AddWithValue("#parameter1", myparameter1);
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.Info($"{rows} rows were deleted");
}
I am using AdomdConnection connection class to connect to the Cube. I am using following code.
using (var conn = new AdomdConnection(ConnString))
{
conn.Open();
var cube = conn.Cubes[name];
//Do something
conn.Close();
}
AdomdConnection.ConnectionTimeout Property does not have setter property.
The default value for connectionTimeOut property is 0, which sets the time to infinite.
I have two questions:
Is there any way to set the timeout property for AdomdConnection?
When the cube is busy and your try to run the program, after creating the connection when you open the connection (conn.open()), system does not come out of this statement & never executes the next line of code. In such cases the application becomes irresponsible and there is no exception thrown. How can I inform user about such scenarios & make a log entry.
I looked into this similar tread but did not found it useful.
Thank you
The documentation states this for AdomdConnection.ConnectionTimeout
Gets the time to wait for a connection to be established before the
AdomdConnection stops trying to connect and generates an error.
So that means the timeout just talking to the server.
If you want a timeout when your running an actual command use the AdomdCommand.CommandTimeout property.
Gets or sets the time to wait for a command to run before the
AdomdCommand stops trying to run the command and generates an error.
Both can be set with the connection string.
http://msdn.microsoft.com/en-us/library/microsoft.analysisservices.adomdclient.adomdconnection.connectionstring.aspx
I am developing a .NET web application with C# and SQL Server as database, being newbie for both technologies. I have a problem when I attempt to save a lot of information at the same time.
My code is simple:
SqlConnection cn = null;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (cn = Util.getConnection())
{
cn.Open();
BusinessObject.saveObject1(param1, cn);
BusinessObject.saveObject2(param2, cn);
BusinessObject.saveObject3(param3, cn);
BusinessObject.saveObject4(param4, cn);
...
scope.Complete();
}
}
I always use the same connection object because if an error happens, I must revoke any change in my data and the same behaviour if the process is ok, is needed.
I don't mind it the process of saving takes a lot of time, in my application is perfectly normal because I have to save a lot of information.
The weirdness here is:
When I execute this function in the same local area network of the database, it perfectly works.
However, if I execute it from outside, such as, connected by a VPN and consequently with higher latency, I get an error with the message: "The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements."
I have tried to change the timeout of the database through the connection string in the web.config but it didn't resolve anything. Also, if after each executeNonQuery() statement I do a cn.Dispose(), I get an error in the next attempt to use the connection object.
Do I have to change the parameters of TransactionScope object? Is there another better way to do this?
Thanks in advanced.
This is due to a timeout error. The TransactionScope might decide to rollback the transaction in case of a timeout.
You need to increase the timeout value in the TransactionScope constructor. The default max. timeout is 10min.
Move scope.Complete(); outside the connection block (MSDN article).
Did you try setting the Timeout = 0 in your Util.getConnection() function ? A value of 0 indicates no limit. This will complete the job surely. By setting the Timeout = 0 will complete every long operation job.